Search code examples
phparrayspivotgrouping

Pivot an indexed array of associative arrays


I want to convert this:

$arr = [
    [
        'type' => 'fruit',
        'name' => 'apple',
        'cost' => 1
    ],
    [
        'type' => 'fruit',
        'name' => 'orange',
        'cost' => 2
    ],
    [
        'type' => 'vegetable',
        'name' => 'carrot',
        'cost' => 2.5
    ],
    [
        'type' => 'vegetable',
        'name' => 'avocado',
        'cost' => 3.5
    ]
];

Into this:

$arr = [
    [
        'type' => 'fruit',
        'apple' => '1',
        'orange' => 2
    ],
    [
        'type' => 'vegetable',
        'carrot' => 2.5,
        'avocado' => 3.5
    ]
];

As you can see, I'm needing to group each type in a single array and pivoting fruit name and cost.


Solution

  • Here's a method for obtaining that exact array structure in the output. This was a touch trickier than I thought it would be:

    //first build groups by type
    $groups = array();
    
    foreach($arr as $key => $array){
        //$type is not necessary, it's just for clarity below
        $type = $array['type'];
    
        if( !isset($groups[$type]) ){
            $groups[$type] = array();
            $groups[$type]['type'] = $array['type'];
        }
        $groups[$type][$array['name']] = $array['cost'];
    
    }
    //then combine the groups into a master array
    $out = array();
    foreach($groups as $g){
        $out[] = $g;
    }
    echo '<pre>'. print_r($out, true).'</pre>';