0

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.

2 Answers 2

2

Create a function which iterates through the array, generating the type of array you want. There is no builtin method.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.