2010-06-29 153 views
0

我怎麼能低於PHP處理陣列問題

Array 
(
    [0] => stdClass Object 
     (
      [name] => color 
      [value] => red 
     ) 

    [1] => stdClass Object 
     (
      [name] => color 
      [value] => black 
     ) 

    [2] => stdClass Object 
     (
      [name] => color 
      [value] => green 
     ) 

    [3] => stdClass Object 
     (
      [name] => volume 
      [value] => 15L 
     ) 

    [4] => stdClass Object 
     (
      [name] => volume 
      [value] => 25L 
     ) 

) 

的數組轉換成一個像這樣的

Array(
    'colors' => red, black, green 
    'volumes' => 15L, 25L 
) 

此代碼

foreach($result as $r) 
    {   
     if($mem !== $r->name) unset($attribs[$r->name . "s"]);    
     $string .= $r->value . ", ";      
     $attribs[$r->name . "s"] = reduce_multiples($string, ", ", TRUE); //removes the last comma from the string   
     $mem = $r->name;      
    } 

打印出

Array 
(
    [colors] => red, black, green 
    [volumes] => red, black, green, 15L, 25L 
) 

$ result是上面的第一個數組片段。這很接近,但不是那樣。該生產線

if($mem !== $r->name) unset($attribs[$r->name . "s"]); 

無助的時刻,但我認爲這是沿着這些線路,我需要從卷省略「紅,黑,綠」的東西。

回答

1
$newArray = array(); 
foreach($oldArray as $obj) { 
    $name = $obj->name.'s'; 
    $value = $obj->value; 
    if array_key_exists($name,$newArray) { 
     $newArray[$name] .= ', '.$value; 
    } else { 
     $newArray[$name] = $value; 
    } 
} 
var_dump($newArray); 
2

創建一個遍歷數組的函數,生成你想要的數組類型。沒有內建的方法。

+0

這就是我所做的,但還沒有那麼... ... – stef 2010-06-29 10:26:39