如何转换下面的数组
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"]);
目前什么都不做,但我认为这些都是我需要省略卷中的“红色,黑色,绿色”。
答案 0 :(得分:2)
创建一个迭代数组的函数,生成所需的数组类型。没有内置方法。
答案 1 :(得分: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);