Search code examples
phparraysmultidimensional-arraygrouping

Group 2d array data using column value to create a 3d array


I have a multidimensional array and am trying to group them according to the value in a specific column.

I'm trying to group them by level, but I won't actually know the level beforehand. So, it's not like I can put it in a for loop and say while $i < 7, because I won't know that 7 is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did.

[
    ['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
    ['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
    ['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
    ['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
    ['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]

Desired result:

Array (

   [1] => Array (
          [0] => Array (
                    [cust] => XT8900
                    [type] => standard
                    )
          [1] => Array (
                    [cust] => XT8944
                    [type] => standard
                    )
          )

   [3] => Array (
          [2] => Array (
                 [cust] => XT8922
                 [type] => premier
                 )

          [3] => Array (
                 [cust] => XT8816
                 [type] => permier
                 )
          )

   [7] => Array (
          [4] => Array (
                 [cust] => XT7434
                 [type] => standard
                 )
          )
)

Solution

  • You need to group them by level first

    Use foreach to loop into array check if the level is the same with the previous item then group it with that array

      $templevel=0;   
    
      $newkey=0;
    
      $grouparr[$templevel]="";
    
      foreach ($items as $key => $val) {
       if ($templevel==$val['level']){
         $grouparr[$templevel][$newkey]=$val;
       } else {
         $grouparr[$val['level']][$newkey]=$val;
       }
         $newkey++;       
      }
    print($grouparr);
    

    The output of print($grouparr); will display like the format you hoped for

    You can also try to

    print($grouparr[7]);
    

    Will display

     [7] => Array (
          [4] => Array (
                 [cust] => XT7434
                 [type] => standard
                 )
          )
    

    Or

    print($grouparr[3]);
    

    Will display

    [3] => Array (
          [2] => Array (
                 [cust] => XT8922
                 [type] => premier
                 )
    
          [3] => Array (
                 [cust] => XT8816
                 [type] => permier
                 )
          )