我有以下数组:
$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
大卫·琼斯(1条评论)
- 2011-05-10 11:26:00 |测试注释 2
一种解决方案是按名称字段对它们进行排序(请查看 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
}
}
我建议使用第二个分组数组
$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";
}
}
你应该尝试采用多维数组。
$comment_groups[] = array();
$m_id = '';
foreach( $comment_groups as $key=>$val ) {
if($key == 'member_id'){
$m_id = $val;
}
$comment_groups[$m_id]][] = $val;
}
然后,您可以根据需要进行打印。