我有一个这样的数组:
Array
(
[0] => Array
(
[id] => 2
[type] => comment
[text] => hey
[datetime] => 2010-05-15 11:29:45
)
[1] => Array
(
[id] => 3
[type] => status
[text] => oi
[datetime] => 2010-05-26 15:59:53
)
[2] => Array
(
[id] => 4
[type] => status
[text] => yeww
[datetime] => 2010-05-26 16:04:24
)
)
有没有人能建议一种基于datetime元素的排序方法?
发布于 2016-11-07 18:34:33
在php7中,可以使用Spaceship operator
usort($array, function($a, $b) {
return new DateTime($a['datetime']) <=> new DateTime($b['datetime']);
});
发布于 2010-05-26 14:46:27
http://us2.php.net/manual/en/function.array-multisort.php参见第三个示例:
<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
仅供参考,使用unix (1970年的秒数)或mysql时间戳(YmdHis - 20100526014500)对于解析器来说会更容易,但我认为在您的情况下没有什么不同。
发布于 2014-12-11 19:58:35
$array = Array
(
[0] => Array
(
[id] => 2
[type] => comment
[text] => hey
[datetime] => 2010-05-15 11:29:45
)
[1] => Array
(
[id] => 3
[type] => status
[text] => oi
[datetime] => 2010-05-26 15:59:53
)
[2] => Array
(
[id] => 4
[type] => status
[text] => yeww
[datetime] => 2010-05-26 16:04:24
)
);
print_r($array);
$name = 'datetime';
usort($array, function ($a, $b) use(&$name){
return $a[$name] - $b[$name];});
print_r($array);
https://stackoverflow.com/questions/2910611
复制相似问题