[英]PHP array sort by value and date (2 columns)
我在PHP中有多维数组。 就像是
$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()函数,因为这涉及时间。
这就是我现在所拥有的
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');
谁能帮助我实现这一目标?
看来您需要array_multisort。 您可以访问以下链接以获取更多信息http://www.php.net//manual/en/function.array-multisort.php
基本想法将从上面链接的example#2中清除。
第二个usort
覆盖第一个usort
的输出。
您需要做的是合并这2个排序功能,以按标题和日期时间对其进行排序。
伪代码为:
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)
。
尝试这个,
$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'),
array('ID' => 5, 'title' => 'Boy', 'datetime' => '2014-05-01 5:08 PM')
);
// Obtain a list of columns
foreach ($mylist as $key => $row) {
$dTime[$key] = $row['datetime'];
$title[$key] = $row['title'];
}
// Sort the data with dTimedescending, titleascending
// Add $mylist as the last parameter, to sort by the common key
array_multisort($dTime, SORT_DESC, $title, SORT_ASC, $mylist);
您的输出将是
Array
(
[0] => Array
(
[ID] => 2
[title] => Amazing Pic
[datetime] => 2014-05-06 11:08 PM
)
[1] => Array
(
[ID] => 1
[title] => Hello
[datetime] => 2014-05-05 12:08 PM
)
[2] => Array
(
[ID] => 3
[title] => Style
[datetime] => 2014-05-02 9:08 PM
)
[3] => Array
(
[ID] => 5
[title] => Boy
[datetime] => 2014-05-01 5:08 PM
)
[4] => Array
(
[ID] => 4
[title] => Hello World
[datetime] => 2014-05-01 5:08 PM
)
)
我添加了ID号5进行演示,以便日期按降序排序,标题按升序排序
我最终得到了马克·加布里埃尔(Mark Gabriel)的逻辑。 这将首先对标题进行排序,然后对日期时间进行排序。 所以这里是:
function SortByTitleAndDateTime($a,$b){
if ( strcasecmp($a['title'], $b['title']) != 0 ){
return strcasecmp($a['title'], $b['title']);
}
else{
$ad = strtotime($a['datetime']);
$bd = strtotime($b['datetime']);
return ($ad-$bd);
}
}
usort($mylist, 'SortByTitleAndDateTime');
希望这对其他人也有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.