0

我有一个数组 $history:

Array (
Array ([id] => 1, [created] => 2012-12-20 22:40, [message] => 'Message1 to display here'),
Array ([id] => 2, [created] => 2012-12-20 22:40, [message] => 'Message2 to display here'),
Array ([id] => 3, [created] => 2012-12-20 22:40, [message] => 'Message3 to display here'),
Array ([id] => 4, [created] => 2012-12-20 21:30, [message] => 'Message4 to display here'),
Array ([id] => 5, [created] => 2012-12-20 21:30, [message] => 'Message5 to display here'),
Array ([id] => 6, [created] => 2012-12-20 20:20, [message] => 'Message6 to display here'),
);

我想显示按日期 [创建] 字段分组的消息 [消息]。

喜欢

2012-12-20 22:40
======================
Message1
Message2
Message3

2012-12-20 21:30
======================
Message4
Message5

我知道有一个函数 array_count_values() 可以提供帮助。

4

3 回答 3

2
$arr_by_dates = array();
foreach($arr as $a){
    if (!isset($arr_by_dates[$a['created']])){
        $arr_by_dates[$a['created']] = array();
    }
    $arr_by_dates[$a['created']][] = $a['message'];
}

如果要在每条记录上保存其他信息,可以使用数组而不是消息本身:

$arr_by_dates = array();
foreach($arr as $a){
    if (!isset($arr_by_dates[$a['created']])){
        $arr_by_dates[$a['created']] = array();
    }
    $arr_by_dates[$a['created']][] = $a;
    // or  = array('message'=>$a['message'], 'id'=>$a['id']);
}
于 2012-12-21T14:25:23.927 回答
1

希望这可以帮助:

$keys = array();
foreach ($arr as $item) 
{
    $keys[] = strtotime($item['created']);
}
sort($keys);
array_multisort($arr, $keys);
于 2012-12-21T14:27:30.967 回答
0

您可以转换您的结构,然后逐步进行打印

$grouped = array();
foreach( $histories as $row ) {
  $date = $row['created'];
  if ( isset($grouped[$date]) ) {
    $grouped[$date][] = $row;
  }
  else {
    $grouped[$date] = array($row);
  }
}

或者您可以随时打印,后者将取决于您按created日期排序的结果:

$last = $html = '';
foreach( $histories as $row ) {
  $date = $row['created'];
  if ( $last != $date ) {
    if ( $last ) $html .= '</div>';
    $html .= '<div>';
    $html .= '<h3>'.$date.'</h3>';
    $last = $date;
  }
  $html .= '<p>'.$row['message'].'</p>';
}
$html .= ($html?'</div>':'');
于 2012-12-21T14:28:56.163 回答