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

59,053

Solution 1

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

Solution 2

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.

Solution 3

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;

Solution 4

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

Solution 5

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); 
Share:
59,053
n00b0101
Author by

n00b0101

Updated on December 18, 2020

Comments

  • n00b0101
    n00b0101 over 3 years

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

    Array (
       [0] => Array (
              [cust] => XT8900
              [type] => standard
              [level] => 1
              )
       [1] => Array (
              [cust] => XT8944
              [type] => standard
              [level] => 1
              )
       [2] => Array (
              [cust] => XT8922
              [type] => premier
              [level] => 3
              )
       [3] => Array (
              [cust] => XT8816
              [type] => permier
              [level] => 3
              )
       [4] => Array (
              [cust] => XT7434
              [type] => standard
              [level] => 7
              )
    )
    

    What I'm hoping to produce:

    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
                     )
              )
    )
    
  • drew schmaltz
    drew schmaltz about 10 years
    this is such a useful answer. I'm trying to use this but to have $val be a unique value. Suggestions?
  • mickmackusa
    mickmackusa over 5 years
    Not only does this post do a poor job of explaining itself, it doesn't increment the subarray keys as required by the OP. Furthermore, it doesn't even dignify the key values from the question -- account_id has nothing to do with this question. For all of these reasons, I am surprised that it has gained so many upvotes and I have downvoted as a matter of principle. Proof: sandbox.onlinephpfunctions.com/code/… I care about the quality of old content on this site, because I use it to close new questions when appropriate.
  • mickmackusa
    mickmackusa over 5 years
    This answer doesn't not provide the OP's desired output because it is not incrementing the subarray keys. Proof: sandbox.onlinephpfunctions.com/code/…
  • mickmackusa
    mickmackusa over 5 years
    Code-only answers are low value on StackOverflow because they do a poor job of educating the OP and future researchers -- every answer (even basic ones) should include some sort of explanation about how the solution works and why it is advisable. This answer does NOT provide the desired output as dictated by the question because it does not increment the subarray keys. Proof: sandbox.onlinephpfunctions.com/code/…
  • mickmackusa
    mickmackusa over 5 years
    This answer supplies no logic nor explanation. I don't have any idea what $key and $keyName are meant to hold. I have downvoted this answer because I can't make sense of it and I don't know what values to feed the function.
  • Nick
    Nick over 5 years
    Code-only answers are discouraged. Please click on edit and add some words summarising how your code addresses the question, or perhaps explain how your answer differs from the previous answer/answers. Thanks
  • vasilis
    vasilis over 3 years
    I think the 'if' clause in your code above is redundant, since the line " $grouparr[$val['level']][$newkey]=$val; " works for all cases. In other words, this line holds true also for the case that '$templevel' is equal to '$val['level']'. So, in that case, the code would just be: $templevel=0; $newkey=0; foreach ($items as $key => $val) { $grouparr[$val['level']][$newkey]=$val; $newkey++; } print($grouparr);