How to group a multidimensional array by a particular subarray value?

Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.

If not then build a temporary array to sort:

foreach ($input_arr as $key => &$entry) {
    $level_arr[$entry['level']][$key] = $entry;
}

Leaves you with the form you wanted and everything referenced together.

Build the array like that in the first place though if at all possible.


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
             )
      )

Here is the solution I landed on for an identical problem, wrapped as a function:

function arraySort($input,$sortkey){
  foreach ($input as $key=>$val) $output[$val[$sortkey]][]=$val;
  return $output;
}

To sort $myarray by the key named "level" just do this:

$myArray = arraySort($myArray,'level');

Or if you didn't want it as a function, just for a one time use, this would create $myNewArray from $myArray grouped by the key 'level'

foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val;

function group_assoc($array, $key) {
    $return = array();
    foreach($array as $v) {
        $return[$v[$key]][] = $v;
    }
    return $return;
}

//Group the requests by their account_id
$account_requests = group_assoc($requests, 'account_id');

Best ans.

    $levels = array_unique(array_column($records, 'level'));

    $data = array();

    foreach($records as $key => $value){ 

    $data[$levels[array_search($value['level'],$levels )]][] = $value ; 

    }

    print_r($data);