我有一个数组$历史:
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()可以提供帮助。
答案 0 :(得分: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']);
}
答案 1 :(得分:1)
希望这会有所帮助:
$keys = array();
foreach ($arr as $item)
{
$keys[] = strtotime($item['created']);
}
sort($keys);
array_multisort($arr, $keys);
答案 2 :(得分: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>':'');