Reputation: 27749
How can I convert the array below
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
)
)
To one like this
Array(
'colors' => red, black, green
'volumes' => 15L, 25L
)
This code
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;
}
Prints out
Array
(
[colors] => red, black, green
[volumes] => red, black, green, 15L, 25L
)
$result is the first array snippet above. It's close but not quite there. The line
if( $mem !== $r->name ) unset($attribs[$r->name . "s"]);
does nothing for the moment but I think it's something along these lines that I need to omit the "red, black, green" from the volumes.
Upvotes: 0
Views: 291
Reputation: 212412
$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);
Upvotes: 1
Reputation: 43243
Create a function which iterates through the array, generating the type of array you want. There is no builtin method.
Upvotes: 2