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

Sort array by specific value with usort

我知道存在类似的线程,我已尝试理解并阅读所有线程,但我一无所获。

问题:我想输出斯坦利库布里克导演的所有电影,我希望这些电影按发行年份降序排列。

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

"crew": [
    {
      "id": 45966,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Day of the Fight",
      "job": "Director of Photography",
      "overview": "American short subject documentary film in black-and-white, which is notable as the first picture directed by Stanley Kubrick. Kubrick financed the film himself, and it is based on an earlier photo feature he had done as a photographer for Look magazine in 1949. 'Day of the Fight' shows Irish-American middleweight boxer Walter Cartier during the height of his career, on the day of a fight with black middleweight Bobby James, which took place on April 17, 1950.",
      "vote_count": 69,
      "video": false,
      "poster_path": "/4caX3IZkf7n2QCbxaJO3hyn0SCm.jpg",
      "backdrop_path": "/lt1Lan9bmG29JjqaMad5tkRpCHJ.jpg",
      "title": "Day of the Fight",
      "popularity": 4.701,
      "genre_ids": [
        99
      ],
      "vote_average": 5.9,
      "adult": false,
      "release_date": "1951-04-26",
      "credit_id": "55d0b196c3a3681bff007bde"
    },
    {
      "id": 10165,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Fear and Desire",
      "job": "Director of Photography",
      "overview": "After their airplane crashes behind enemy lines, four soldiers must survive and try to find a way back to their battalion. However, when they come across a local peasant girl the horrors of war quickly become apparent.",
      "vote_count": 254,
      "video": false,
      "poster_path": "/oiN9OUOGbVywUHjto30AfLpnIJ7.jpg",
      "backdrop_path": "/e3o0Dwlzzpd4kJpOOJgVyMstnII.jpg",
      "title": "Fear and Desire",
      "popularity": 6.052,
      "genre_ids": [
        18,
        10752
      ],
      "vote_average": 5.5,
      "adult": false,
      "release_date": "1953-04-01",
      "credit_id": "55d0b9c392514131a5007a4c"
    },
    {
      "id": 45314,
      "department": "Camera",
      "original_language": "en",
      "original_title": "The Seafarers",
      "job": "Director of Photography",
      "overview": "Acclaimed director Stanley Kubrick's first film made in color. The documentary focuses on the benefits of membership to the Seafarers International Union.",
      "vote_count": 44,
      "video": false,
      "release_date": "1953-10-15",
      "vote_average": 4.7,
      "title": "The Seafarers",
      "popularity": 3.009,
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "poster_path": "/nSucFIAQ5CowEE1WZ87mz3OsbQ1.jpg",
      "credit_id": "55d0cae1c3a36877570014d2"
    },
    {
      "id": 975,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Paths of Glory",
      "job": "Additional Photography",
      "overview": "A commanding officer defends three scapegoats on trial for a failed offensive that occurred within the French Army in 1916.",
      "vote_count": 1613,
      "video": false,
      "poster_path": "/peblNaHOiTR8DACYyUWsJHhK6GP.jpg",
      "backdrop_path": "/yFykLiFuBU6CrGWr2hLP0ttbQ2i.jpg",
      "title": "Paths of Glory",
      "popularity": 11.573,
      "genre_ids": [
        18,
        10752
      ],
      "vote_average": 8.3,
      "adult": false,
      "release_date": "1957-09-18",
      "credit_id": "5706f1259251412b1400065c"
    },
    {
      "id": 45970,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Flying Padre",
      "job": "Director of Photography",
      "overview": "Two days in the life of priest Father Fred Stadtmuller whose New Mexico parish is so large he can only spread goodness and light among his flock with the aid of a mono-plane. The priestly pilot is seen dashing from one province to the next at the helm of his trusty Piper Club administering guidance (his plane, the Flying Padre) to unruly children, sermonizing at funerals and flying a sickly child and its mother to a hospital.",
      "vote_count": 56,
      "video": false,
      "release_date": "1951-03-23",
      "vote_average": 5.2,
      "title": "Flying Padre",
      "popularity": 4.033,
      "genre_ids": [
        99
      ],
      "backdrop_path": "/5HisBYhc75h0DYXSMJWN1eFaxse.jpg",
      "adult": false,
      "poster_path": "/5aog5qVlMFakpogT1Nar9Z7gqq4.jpg",
      "credit_id": "5e94991dccb15f001571103c"
    },
    {
      "id": 10056,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Killer's Kiss",
      "job": "Director of Photography",
      "overview": "The film revolves around Davey Gordon, a 29 year old welterweight New York boxer in the end of his career, and his relationship with a dancer and her violent employer.",
      "vote_count": 283,
      "video": false,
      "poster_path": "/jc5EjvQywJqS8Xm0RWMoblJvCM6.jpg",
      "backdrop_path": "/6VhN0ScAA8VgK3qyRnZ7azD9XEV.jpg",
      "title": "Killer's Kiss",
      "popularity": 10.353,
      "genre_ids": [
        80,
        18,
        53
      ],
      "vote_average": 6.4,
      "adult": false,
      "release_date": "1955-09-21",
      "credit_id": "5e9499448e87020013ce555f"
    },
    {
      "id": 185,
      "department": "Directing",
      "original_language": "en",
      "original_title": "A Clockwork Orange",
      "job": "Director",
      "overview": "In a near-future Britain, young Alexander DeLarge and his pals get their kicks beating and raping anyone they please. When not destroying the lives of others, Alex swoons to the music of Beethoven. The state, eager to crack down on juvenile crime, gives an incarcerated Alex the option to undergo an invasive procedure that'll rob him of all personal agency. In a time when conscience is a commodity, can Alex change his tune?",
      "vote_count": 8571,
      "video": false,
      "release_date": "1971-12-19",
      "vote_average": 8.2,
      "title": "A Clockwork Orange",
      "popularity": 25.023,
      "genre_ids": [
        878,
        18
      ],
      "backdrop_path": "/keblhZFIZYiWflmURWNHEuS2jqL.jpg",
      "adult": false,
      "poster_path": "/4sHeTAp65WrSSuc05nRBKddhBxO.jpg",
      "credit_id": "52fe4224c3a36847f80071db"
    },

到目前为止我的代码

$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>';
   }
}

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

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

 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. 当您拥有所有要排序的项目时,您对 this array
  3. 进行排序
  4. 然后你可以遍历这个排序数组来处理结果,例如显示它们。

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

$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>';
}