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;
});
此外,您還嘗試在錯誤的位置對數組進行排序 - 每次找到導演時,您都會對單個數組進行排序(并且只有一個元素,因此沒有任何變化)。
你需要:
將所有必需的導演項添加到單獨的數組中進行排序
當您有所有要排序的項目時,您可以對該數組進行排序
然后您可以循環遍歷這個排序數組來處理結果,例如顯示它們。
請參閱下面的代碼 - 對步驟進行了注釋,以便您可以了解需要執行的操作:
$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>';
}
- 1 回答
- 0 關注
- 150 瀏覽
添加回答
舉報