[英]PHP uasort() not sorting by 3rd dimension of array
I have an array of $cards and each card possibly contains multiple episodes.我有一组 $cards,每张卡片可能包含多集。 I want to sort the cards by most recent episode air date.
我想按最近一集播出日期对卡片进行排序。
I have a simple uasort() function.我有一个简单的 uasort() 函数。
uasort($cards, function($a, $b) {
return $a['episodes'][0]['air_date'] <=> $b['episodes'][0]['air_date']; // sort in reverse order by latest episode date
});
Here's the resulting $cards array...这是生成的 $cards 数组...
Array
(
[sam] => Array
(
[ID] => 14
[num] => 626
[img] =>
[note] =>
[search_txt] =>
[name] => 626
[status] =>
[episodes] => Array
(
[0] => Array
(
[ID] => 1170
[series_id] => 3
[season_num] => 3
[episode_num] => 1
[card_id] => 14
[air_date] => 2019-09-26
[status] =>
[shaky] => 0
)
)
)
[martha] => Array
(
[ID] => 11
[num] => 628
[img] =>
[note] =>
[search_txt] =>
[name] => 628
[status] =>
[episodes] => Array
(
[0] => Array
(
[ID] => 1173
[series_id] => 3
[season_num] => 3
[episode_num] => 2
[card_id] => 11
[air_date] => 2019-10-03
[status] =>
[shaky] => 0
)
[1] => Array
(
[ID] => 1174
[series_id] => 4
[season_num] => 7
[episode_num] => 2
[card_id] => 11
[air_date] => 2019-10-03
[status] =>
[shaky] => 0
)
)
)
[joey] => Array
(
[ID] => 13
[num] => 627
[img] =>
[note] =>
[search_txt] =>
[name] => 627
[status] =>
[episodes] => Array
(
[0] => Array
(
[ID] => 1171
[series_id] => 4
[season_num] => 7
[episode_num] => 1
[card_id] => 13
[air_date] => 2019-09-27
[status] =>
[shaky] => 0
)
)
)
)
The array is not sorted correctly.数组未正确排序。 it should be sam, joey, martha.
应该是山姆、乔伊、玛莎。 I haven't seen anyone use uasort quite this way, but it seems reasonable to me.
我还没有看到有人以这种方式使用 uasort,但这对我来说似乎是合理的。 Can I go this deep into the array with it?
我可以用它深入到数组中吗? am I just leaving out some important syntax?
我只是遗漏了一些重要的语法吗? I'm not getting any errors.
我没有收到任何错误。
How do I get it to sort by recent episode air_date?我如何让它按最近一集 air_date 排序? Bonus points for sorting by most recent air date.
按最近播出日期排序的奖励积分。
Use the code below使用下面的代码
function date_compare($a, $b)
{
usort($a['episodes'], 'date_compare_inner');
usort($b['episodes'], 'date_compare_inner');
$t1 = strtotime($a['episodes'][0]['air_date']);
$t2 = strtotime($b['episodes'][0]['air_date']);
return $t1 - $t2;
}
function date_compare_inner($a, $b)
{
$t1 = strtotime($a['air_date']);
$t2 = strtotime($b['air_date']);
return $t1 - $t2;
}
usort($cards, 'date_compare');
To sort by the most recent date, then you should extract the list of dates (using array_column()
in this code) and then take the max()
of the dates...要按最近的日期排序,那么您应该提取日期列表
array_column()
在此代码中使用array_column()
),然后获取日期的max()
...
uasort($cards, function($a, $b) {
$a1 = max(array_column( $a['episodes'], 'air_date'));
$b1 = max(array_column( $b['episodes'], 'air_date'));
return $a1 <=> $b1;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.