PHP数组按值和日期排序(2列) [英] PHP array sort by value and date (2 columns)
问题描述
我在PHP中具有多维数组.
I have multidimensional array in PHP. Something like
$mylist = array(
array('ID' => 1, 'title' => 'Hello', 'datetime' => '2014-05-05 12:08 PM'),
array('ID' => 2, 'title' => 'Amazing Pic', 'datetime' => '2014-05-06 11:08 PM'),
array('ID' => 3, 'title' => 'Style', 'datetime' => '2014-05-02 9:08 PM'),
array('ID' => 4, 'title' => 'Hello World', 'datetime' => '2014-05-01 5:08 PM')
);
我的问题是如何按标题和日期时间排序?我花了很多时间对此进行搜索.但是我只是发现按两列进行排序但具有相同的数据类型.我现在正在努力做到这一点,因为我认为我的工作涉及strtotime()函数,因为这涉及时间.
My question is how do I sort by title and datetime? I spent quite some time searching on this. But I just found sort by two columns but with the same data type. I am now struggling to do this because I believe mine involve strtotime() function as this involves time.
这是我目前的状态
function querySort ($x, $y) {
return strcasecmp($x['title'], $y['title']);
}
function cmp($a, $b){
$ad = strtotime($a['datetime']);
$bd = strtotime($b['datetime']);
return ($ad-$bd);
}
usort($mylist , 'querySort');
usort($mylist , 'cmp');
有人可以帮助我实现这一目标吗?
Could anyone help me on how to achieve this?
推荐答案
第二个 usort
覆盖第一个 usort
的输出.
The second usort
overrides the output of the first usort
.
您需要做的是合并两个排序功能,以按标题和日期时间对自身进行排序.
What you need to do is merge the 2 sorting functions to order themselves by title and then date time.
伪代码为:
function SortByTitleAndDateTime($a,$b)
1) SortByTitle and return the value if it is non zero.
2) If SortByTitle is zero (meaning the 2 values are the same in terms of title),
do SortByDateTime
最后,您只需要调用 usort(array,SortByTitleAndDateTime)
.
这篇关于PHP数组按值和日期排序(2列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!