[英]Filtering array by date
I have an array filled with items.我有一个充满项目的数组。 Every item has a StartDate with the format
d/m/YH:i:s
.每个项目都有一个格式为
d/m/YH:i:s
的 StartDate。
I want to order the array items, from earliest to last.我想从最早到最后订购数组项目。
I already tried doing我已经尝试过
$client = [ [ 'LessonId' => 1, 'StartTime' => '20/11/2022 10:30:00', 'EndTime' => '20/11/2022 11:30:00', 'LessonName' => 'Dance', ], [ 'LessonId' => 2, 'StartTime' => '20/11/2022 09:30:00', 'EndTime' => '20/11/2022 10:30:00', 'LessonName' => 'Dance', ], ];
usort($client, function ($a, $b) {
$pos_a = strtotime(\DateTime::createFromFormat('d/m/Y H:i:s', $a['StartTime']));
$pos_b = strtotime(\DateTime::createFromFormat('d/m/Y H:i:s', $b['StartTime']));
return $pos_a <=> $pos_b;
});
Sadly it's not working since the array is still in it's old order.可悲的是,它不起作用,因为阵列仍处于旧状态。 I'm not even sure if I still need
strtotime()
since I already tell php which date format the fields are.我什至不确定是否还需要
strtotime()
,因为我已经告诉 php 字段是哪种日期格式。
At first it didn't work because one or more values returned false.起初它不起作用,因为一个或多个值返回 false。 Later after figuring that out, I managed to fix it by converting the dates to a time stamp.
后来弄清楚这一点后,我设法通过将日期转换为时间戳来修复它。 and doing:
并做:
usort($arrayToSort , function ($a, $b) {
if($a['startTime'] == null && $b['startTime'] == null) return 0;
if($a['startTime'] == null) return 1; //1 -> "a is greater than b"
if($b['startTime'] == null) return -1; //-1 -> "a is less than b"
return $a['startTime'] <=> $b['startTime'];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.