为了账号安全,请及时绑定邮箱和手机立即绑定

使用 usort 按特定值对数组进行排序

使用 usort 按特定值对数组进行排序

PHP
慕丝7291255 2023-10-15 15:09:51
我知道存在类似的线程,并且我尝试理解并阅读它们,但我没有任何进展。问题:我想输出斯坦利·库布里克执导的所有电影,并且希望电影按上映年份降序排列。电影的输出有效,但我无法对它们进行排序。到目前为止我的代码$data = file_get_contents($url); // put the contents of the file into a variable$director = json_decode($data); // decode the JSON feedecho '<pre>';print_r($director);foreach ($director->crew as $showDirector) {    if ($showDirector->department == 'Directing') {        usort($showDirector, function ($item1, $item2) {            return $item2['release_date'] <=> $item1['release_date'];        });        echo $showDirector->release_date . ' / ' . $showDirector->title . '<br>';   }}
查看完整描述

1 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

usort完全按原样传递数组中的元素。即在这种情况下,您的数组包含对象- 因此您需要对对象的属性进行比较,而不是作为数组中的元素进行比较。


而不是像这样将项目作为数组元素进行比较:


 return $item2['release_date'] <=> $item1['release_date']);

...您的函数应该像这样检查对象属性:


usort($showDirector, function ($item1, $item2) {

    /* Check the release_date property of the objects passed in */

    return $item2->release_date <=> $item1->release_date;

});

此外,您还尝试在错误的位置对数组进行排序 - 每次找到导演时,您都会对单个数组进行排序(并且只有一个元素,因此没有任何变化)。

你需要:

  1. 将所有必需的导演项添加到单独的数组中进行排序

  2. 当您有所有要排序的项目时,您可以对该数组进行排序

  3. 然后您可以循环遍历这个排序数组来处理结果,例如显示它们。

请参阅下面的代码 - 对步骤进行了注释,以便您可以了解需要执行的操作:

$data = file_get_contents($url); // put the contents of the file into a variable

$director = json_decode($data); // decode the JSON feed


/* 1. Create an array with the items you want to sort */

$directors_to_sort = array();

foreach ($director->crew as $showDirector) {

    if ($showDirector->department == 'Directing') {

        $directors_to_sort[] = $showDirector;

    } 

}


/* 2. Now sort those items

   note, we compare the object properties instead of trying to use them as arrays */

usort($directors_to_sort, function ($item1, $item2) {

    return $item2->release_date <=> $item1->release_date;

});


/* 3. Loop through the sorted array to display them */

foreach ($directors_to_sort as $director_to_display){

    echo $director_to_display->release_date . ' / ' . $director_to_display->title . '<br>';

}


查看完整回答
反对 回复 2023-10-15
  • 1 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信