Search code examples
phparraysmultidimensional-arraygrouping

How to restructure an array of single-element associative arrays into grouped subarrays?


I have an associative array:

Array ( 
[0] => Array ( [term_title] => black ) 
[1] => Array ( [color_quantity] => 2 ) 
[2] => Array ( [color_price] => 22 ) 
[3] => Array ( [term_title] => blue ) 
[4] => Array ( [color_quantity] => 3 ) 
[5] => Array ( [color_price] => 33 ))

How can I change it into:

Array ( 
[0] => Array ( [term_title] => black, [color_quantity] => 2, [color_price] => 22 ) 
[1] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) )

I try the following code:

$post = array();
for($i = 0; $i < 2; $i++){
    foreach($feild_data as $data){
        $post[$i][$data['name']] = $data['value'];
    }
}

but it repeat the last index two times. i.e.

Array ( 
[0] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) 
[1] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) )

Solution

  • If you like language constructs and basic arithmetic, then you can simply loop through the array, divide by 3 and use that float value as the first level key -- php will automatically floor() that value to form an integer

    Code: (Demo)

    foreach ($array as $index => $subarray) {
        $key = key($subarray);
        $result[intdiv($index, 3)][$key] = $subarray[$key];
    }
    var_export($result);
    

    Alternatively, if you prefer functional syntax (and I often do), you can form groups of subarrays, then merge/flatten the groups. The technique below does not require the declaration of a $result variable and could be written as a one-liner.

    Code: (Demo)

    var_export(
        array_map(
            function($v) {
                return array_merge(...$v);
            },
            array_chunk($array, 3)
        )
    );
    

    Both techniques provide the following output:

    array (
      0 => 
      array (
        'term_title' => 'black',
        'color_quantity' => 2,
        'color_price' => 22,
      ),
      1 => 
      array (
        'term_title' => 'blue',
        'color_quantity' => 3,
        'color_price' => 33,
      ),
    )