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

我知道存在类似的线程,并且我尝试理解并阅读它们,但我没有任何进展。

问题:我想输出斯坦利·库布里克执导的所有电影,并且希望电影按上映年份降序排列。

电影的输出有效,但我无法对它们进行排序。

到目前为止我的代码


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

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


echo '<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>';

   }

}


慕丝7291255
浏览 64回答 1
1回答

三国纷争

usort完全按原样传递数组中的元素。即在这种情况下,您的数组包含对象- 因此您需要对对象的属性进行比较,而不是作为数组中的元素进行比较。而不是像这样将项目作为数组元素进行比较:&nbsp;return $item2['release_date'] <=> $item1['release_date']);...您的函数应该像这样检查对象属性:usort($showDirector, function ($item1, $item2) {&nbsp; &nbsp; /* Check the release_date property of the objects passed in */&nbsp; &nbsp; return $item2->release_date <=> $item1->release_date;});此外,您还尝试在错误的位置对数组进行排序 - 每次找到导演时,您都会对单个数组进行排序(并且只有一个元素,因此没有任何变化)。你需要:将所有必需的导演项添加到单独的数组中进行排序当您有所有要排序的项目时,您可以对该数组进行排序然后您可以循环遍历这个排序数组来处理结果,例如显示它们。请参阅下面的代码 - 对步骤进行了注释,以便您可以了解需要执行的操作:$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) {&nbsp; &nbsp; if ($showDirector->department == 'Directing') {&nbsp; &nbsp; &nbsp; &nbsp; $directors_to_sort[] = $showDirector;&nbsp; &nbsp; }&nbsp;}/* 2. Now sort those items&nbsp; &nbsp;note, we compare the object properties instead of trying to use them as arrays */usort($directors_to_sort, function ($item1, $item2) {&nbsp; &nbsp; return $item2->release_date <=> $item1->release_date;});/* 3. Loop through the sorted array to display them */foreach ($directors_to_sort as $director_to_display){&nbsp; &nbsp; echo $director_to_display->release_date . ' / ' . $director_to_display->title . '<br>';}
打开App,查看更多内容
随时随地看视频慕课网APP