1

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
0

3 Answers 3

4

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
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Also note that you can get the comments sorted by the author's name using ksort after the first foreach loop.
When using square brace pushing syntax, it is not necessary to instantiate an empty array before pushing children into it.
2

I would suggest using a second grouping array

$groups[] = array();
foreach( $comment as $k=>$v ) {
    $groups[$v['member_id']][] = $k
}

And then to print it

foreach( $group as $m_id=>$arr ) {
    echo "Group $m_id<br/>\n";
    foreach( $arr as $k ) {
        echo $comment[$k]."<br/>\n";
    }
}

Comments

1

You should try with taking multi-dimensional array.

 $comment_groups[] = array();
    $m_id = '';

    foreach( $comment_groups as $key=>$val ) {
         if($key == 'member_id'){
             $m_id = $val;
            }
           $comment_groups[$m_id]][] = $val;
   }

Then you can print as you want to display.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.