亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 150 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號