phparraysmultidimensional-arraygroupingmerging-data

Group data from a 3-level array data by a second level column and merge the third level data per group


I want to group the following data by the first column and merge the other column's subarray data per group.

$arr = [
    [0, [0 => 'abc']],
    [0, [1 => 'def']],
    [1, [0 => 'ghi']],
];

Desired result:

Array
    (
       [0] => Array
           (
              [0] => 'abc'
              [1] => 'def'
            )
            
       [1] => Array
           (
               [0] => 'ghi'
            )
                
    )

Solution

  • I'm not 100% sure I've understood what you want, but if I have, this should work:

    <?php
    
    $arr = Array(
        0 => Array(0, Array(0=>'abc')),
        1 => Array(0, Array(1=>'def')),
        2 => Array(1, Array(0=>'ghi'))
    );
    
    
    function transformArray($array) {
        $newArray = array();
    
        foreach ($array as $value) {
            if (!isset($newArray[$value[0]])) {
                $newArray[$value[0]] = array();
            }
            $newArray[$value[0]][] = array_pop($value[1]);
        }
    
        return $newArray;
    }
    
    
    $outputArray = transformArray($arr);
    echo '<pre>' . print_r($outputArray, true) . '</pre>';
    
    ?>