Search code examples
phparraysmultidimensional-arraygroupingsub-array

Group rows of a 2d array by a column value and push whole rows into grouped subarrays


i've got the following array:

$comments   = array();
$comments[] = array('member_id' => '17',
                    'time'      => '2011-05-10 11:10:00',
                    'name'      => 'John Smith',
                    'comment'   => 'Test Comment 1');
$comments[] = array('member_id' => '25',
                    'time'      => '2011-05-10 11:26:00',
                    'name'      => 'David Jones',
                    'comment'   => 'Test Comment 2');
$comments[] = array('member_id' => '17',
                    'time'      => '2011-05-10 13:15:00',
                    'name'      => 'John Smith',
                    'comment'   => 'Test Comment 3');

How would i go about grouping it by member_id? So I'll be able to display the comments on the page with the following formatting:

John Smith(2 comments)

  • 2011-05-10 11:10:00 | Test Comment 1
  • 2011-05-10 13:15:00 | Test Comment 3

David Jones(1 comment)

  • 2011-05-10 11:26:00 | Test Comment 2

Solution

  • One solution is to sort them by the name field (check out usort for that), but even easier might be to just populate a new array in this way:

    $grouped = array();
    foreach($comments as $c) {
      if(!isset($grouped[$c['name']]) {
        $grouped[$c['name']] = array();
      }
    
      $grouped[$c['name']][] = $c;
    }
    
    //Now it's just a matter of a double foreach to print them out:
    foreach($grouped as $name => $group) {
      //print header here
      echo $name, "<br>\n";
    
      foreach($group as $c) {
        //print each comment here
      }
    }