Search code examples
phparraysforeachassociative-array

Convert an array of objects to an array of associative arrays


I am using this to create an array:

foreach ($results as $tire) {
    $group_price[] = array($tire->group, $tire->price);
}

My results are:

Array ( 
    [0] => Array (
        [0] => MAXAT 
        [1] => 118.91 
        ) 
    [1] => Array (
        [0] => FZSUV 
        [1] => 137.81 
    ) 
    [2] => Array ( 
        [0] => MAXAT 
        [1] => 153.79 
    )
)

What I would like my results to be:

Array (
    [0] => Array (
        [group] => MAXAT 
        [price] => 118.91
    )
    [1] => Array (
        [group] => FZSUV 
        [price] => 137.81
    )
    [2] => Array (
        [group] => MAXAT 
        [price] => 153.79
    )
)

I am just not sure how to change my foreach in a way that would change the output.


Solution

  • Like so:

    foreach($results as $tire){
        $group_price[] = array(
            'group' => $tire->group,
            'price' => $tire->price
        );
    }