如何按日期重新组织数组,以便在使用foreach()时,所有日期都按顺序排列?
这是我的阵列:
$events = array(
"03/06/2016" => array("Random Data 1","Random Data 2"),
"02/15/2016" => array("Random Data 1","Random Data 2"),
"03/07/2016" => array("Random Data 1","Random Data 2")
);
答案 0 :(得分:2)
要按日期排序,您应将其格式化为Y-m-d
。例如:2016-03-06。
然后使用函数ksort()
对数组中的键值进行排序。
$events = array(
"2016/03/06" => array("Random Data 1","Random Data 2"),
"2016/02/15" => array("Random Data 1","Random Data 2"),
"2016/03/07" => array("Random Data 1","Random Data 2"),
"2015/04/02" => array("Random Data 1","Random Data 2"),
"2015/05/02" => array("Random Data 1","Random Data 2")
);
var_dump($events);
ksort($events);
var_dump($events);
有关日期格式的信息,请参阅:http://php.net/manual/en/function.date.php
对于排序数组的所有函数,请参阅:http://php.net/manual/en/array.sorting.php
答案 1 :(得分:1)
我会做那样的事情:
//objectify & reverse
foreach($arr as $key=>$var) {
$arr2[$var]=new DateTime(substr($key,6,4).'-'.substr($key,0,2).'-'.substr($key,3,2));
}
//sort
asort($arr2);
//re-reverse & format
foreach($arr2 as $key=>$var) {
$var=date_format($var,'m-d-Y');
$arr3[$var]=$key;
}
//read
foreach($arr3 as $key=>$var) {
echo $key.': '.$var;
}
答案 2 :(得分:1)
我们将分两步完成:
// Define array
$events = array(
"03/06/2016" => array("Random Data 1","Random Data 2"),
"02/15/2016" => array("Random Data 1","Random Data 2"),
"03/07/2016" => array("Random Data 1","Random Data 2")
);
// New array
$sortedEvents = array();
// Change key date format
foreach ($events as $date => $randomDates) {
$date = DateTime::createFromFormat('m/d/Y', $date);
$sortedEvents[$date->format('Ymd')] = $randomDates;
}
// Sort new array
ksort($sortedEvents);
// Output array
var_dump($sortedEvents);
答案 3 :(得分:0)
您需要运行 ksort :
$aTmp = array();
$aTmp[ '03/06/2016' ] = '2ttt3t23t2t2';
$aTmp[ '02/15/2016' ] = '2ttt3t23t2t2';
$aTmp[ '03/07/2016' ] = '2ttt3t23t2t2';
var_dump( $aTmp );
ksort( $aTmp );
var_dump( $aTmp );