2011-05-10 137 views
1

我有以下陣列:PHP分組陣列

$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

回答

4

一種解決方案是按name字段進行排序它們(檢查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 
    } 
} 
+0

另請注意,您可以在第一個foreach循環後使用kso​​rt獲取按作者姓名排序的註釋。 – 2011-05-10 12:12:10

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"; 
    } 
} 
1

你應該嘗試採取多維數組。

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

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

然後,您可以打印您想要顯示。