在PHP中对usort排序类似的结果 [英] Sorting similar result in usort in PHP

查看:86
本文介绍了在PHP中对usort排序类似的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这段代码会在最晚开始时间之前对活动数组进行排序,并且还会仅显示循环中第一个具有相同日期的活动.

I understand that this code is sorting up activity array the by latest start time and also just display which any activity that come first in the loop that have same date.

foreach ($activity_array AS $k => $v):
......

usort($v['activity'], function ($a, $b) {
$ad = new DateTime($a['start']);
$bd = new DateTime($b['start']);
if ($ad == $bd) {
return 0;
}
return $ad < $bd ? -1 : 1;
});

如果开始时间相同,但是又有另一个场地变量需要在同一活动中进行排序,我该如何对其进行排序.

How can i sort it if the start time is the same, but got another venue variable that needed to be sort within the same activity.

|  Activity  |  Start         |   Venue   |
+------------+----------------+-----------+
| Activity A | 22/10/17 08.30 | Floor 1   |
| Activity D | 22/10/17 10.30 | Hall 3    |
| Activity B | 22/10/17 10.30 | Hall 1    |
| Activity C | 22/10/17 10.30 | Hall 2    |
| Activity X | 22/10/17 09.30 | Floor 2   |

要像这样:

|  Activity  |  Start         |   Venue   |
+------------+----------------+-----------+
| Activity A | 22/10/17 08.30 | Floor 1   |
| Activity X | 22/10/17 09.30 | Floor 2   |
| Activity B | 22/10/17 10.30 | Hall 1    |
| Activity C | 22/10/17 10.30 | Hall 2    |
| Activity D | 22/10/17 10.30 | Hall 3    |

推荐答案

在开始时间相同的情况下,您可以再次检查场地

You can check again for venue when start time is same

foreach ($activity_array AS $k => $v):
......

usort($v['activity'], function ($a, $b) {
$ad = new DateTime($a['start']);
$bd = new DateTime($b['start']);
if ($ad == $bd) {

    $venue1 = $a['venue'];
    $venue2 = $b['venue'];
    return strcmp($venue1, $venue2);
}
return $ad < $bd ? -1 : 1;
});

这篇关于在PHP中对usort排序类似的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆