Search code examples
phparraysmultidimensional-arraygroupingsub-array

Group rows of a 2d array by the first column and create subarrays within each group


I have a big array (read from a file)

$data = array(
   array(134, 'Field_A_134', 'Field_B_134'),
   array(134, 'Field_C_134', 'Field_D_134'),
   array(134, 'Field_E_134', 'Field_F_134'),
   array(180, 'Field_A_180', 'Field_B_180'),
   array(70, 'Field_A_70', 'Field_B_70'),
   array(180, 'Field_C_180', 'Field_D_180'),
   ...
);

and I want to group into another array by the first key from the first array (ex: 134, 180, 70, ...). Those keys are repeating, but the fields are different.

The array I want to make is:

array(
     '134' => array(array(134, 'Field_A_134', 'Field_B_134'), array(134, 'Field_C_134', 'Field_D_134'), array(134, 'Field_E_134', 'Field_F_134')),
     '180' => array(array(180, 'Field_A_180', 'Field_B_180'), array(180, 'Field_C_180', 'Field_D_180')),
     '70' => array(array(70, 'Field_A_180', 'Field_B_180'))
);

Each key contains an array of arrays that contain the first key.

I was trying to make this:

$f = array();
$pr = array();
foreach($data as $p){
   if(isset($f[$p[0]])){
     array_push($f[$p[0]], $p);
   } else {
     $f[$p[0]] = $p;
   }
   array_push($pr, $f);
}

but it's not what I want.


Solution

  • The error is in the else part. You need to assign an array, like this:

     $f[$p[0]] = [$p];
    

    Or like this, since PHP will create the array on the fly:

     $f[$p[0]][] = $p;
    

    And since that code can also be used when the array already exists, you can simplify to this loop:

    foreach($data as $p) {
        $f[$p[0]][] = $p;
    }