PHP分组数组

时间:2011-05-10 06:16:51

标签: php arrays multidimensional-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');

我如何按member_id对其进行分组?因此,我将能够使用以下格式在页面上显示评论:

约翰史密斯(2评论)

  • 2011-05-10 11:10:00 |测试评论1
  • 2011-05-10 13:15:00 |测试评论3

David Jones(1条评论)

  • 2011-05-10 11:26:00 |测试评论2

3 个答案:

答案 0 :(得分:4)

一种解决方案是按名称字段对它们进行排序(请查看usort),但更简单的方法是以这种方式填充新数组:

$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
  }
}

答案 1 :(得分:2)

我建议使用第二个分组数组

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

然后打印出来

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

答案 2 :(得分:1)

您应该尝试使用多维数组。

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

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

然后您可以根据需要进行打印。