33

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
                 )
          )
)
mickmackusa
  • 33,121
  • 11
  • 58
  • 86
n00b0101
  • 6,643
  • 16
  • 40
  • 36
  • Please forgive me stirring up this old question, but are you expecting the outer keys to be ASC? Is your input array already ordered by level? (because that is what is posted). Look at how the accepted answer behaves with an un-ordered input array: http://sandbox.onlinephpfunctions.com/code/c0ec2e1f7b2b59f0066edd15b05138edf4deed1b Most importantly: Is this data coming from a database? – mickmackusa Aug 24 '18 at 02:51
  • Many of the answers below do not increment the subarray keys. Do you _actually_need the subarray keys to be incremented? – mickmackusa Aug 24 '18 at 03:26

7 Answers7

43

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.

Mike
  • 2,255
  • 1
  • 17
  • 9
11

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
             )
      )
Gerard Banasig
  • 1,595
  • 12
  • 19
  • 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); – vasilis Oct 28 '20 at 10:40
7
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');
Farzher
  • 11,368
  • 15
  • 57
  • 93
  • 2
    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: http://sandbox.onlinephpfunctions.com/code/28f553b4ee2670dc30cb448cfc039bb380b1cba4 I care about the quality of old content on this site, because I use it to close new questions when appropriate. – mickmackusa Aug 24 '18 at 02:57
7

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;
Kevin Hagerty
  • 139
  • 2
  • 5
  • this is such a useful answer. I'm trying to use this but to have $val be a unique value. Suggestions? – drew schmaltz Apr 22 '14 at 04:31
  • This answer doesn't not provide the OP's desired output because it is not incrementing the subarray keys. Proof: http://sandbox.onlinephpfunctions.com/code/22f19e9426fe3133ebd462e469a393730a4e16a1 – mickmackusa Aug 24 '18 at 03:17
1

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); 
  • 1
    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 – Nick Dec 18 '18 at 07:43
0
  $result = array();
    foreach ($yourArrayList as $data) {
        $id = $data['level'];
        if (isset($result[$id])) {
            $result[$id][] = $data;
        } else {
            $result[$id] = array($data);
        }
    }
  • 1
    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: http://sandbox.onlinephpfunctions.com/code/93b556d049b09822383c375d189765e4f3050398 – mickmackusa Aug 24 '18 at 03:21
-2
function _group_by($array,$key,$keyName)
    {
          $return = array();

          foreach($array as $val) {
              $return[$keyName.$val[$key]][] = $val;
          }
         return $return;

    }  //end of function
ketan
  • 17,717
  • 41
  • 50
  • 83
  • 1
    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. – mickmackusa Aug 24 '18 at 03:23