简体   繁体   English

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

[英]Sort array by specific value with usort

I know that similar threads exist, and I have tried to understand and read them all, but I'm not getting anywhere.我知道存在类似的线程,并且我试图理解并阅读它们,但我没有得到任何结果。

Problem: I'd like to output all the films directed by Stanley Kubrick and I want the movies to be listed in descending order by year of release.问题:我想要 output 斯坦利库布里克导演的所有电影,我希望这些电影按上映年份降序排列。

The output of the films works, but I can't sort them.电影的 output 有效,但我无法对其进行排序。

"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"
    },

My code so far到目前为止我的代码

$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 gets passed the elements from the array exactly as they are. usort完全按照原样从数组中传递元素。 ie in this case your array contains objects - therefore you need to do the comparison on the properties of the objects and not as elements in an array.即在这种情况下,您的数组包含对象- 因此您需要对对象的属性进行比较,而不是作为数组中的元素。

Instead of comparing the items as array elements like this:而不是像这样将项目作为数组元素进行比较:

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

...your function should be checking the object properties like this: ...您的 function 应该像这样检查 object 属性:

usort($showDirector, function ($item1, $item2) {
    /* Check the release_date property of the objects passed in */
    return $item2->release_date <=> $item1->release_date;
});

Also, you are also trying to sort the array in the wrong place - each time you find a director, you are sorting that single array (and there is only one element so nothing changes).此外,您还试图在错误的位置对数组进行排序 - 每次找到导演时,您都在对单个数组进行排序(并且只有一个元素,所以没有任何变化)。

You need to:你需要:

  1. Add all of the required director items into a separate array for sorting将所有需要的导演项目添加到单独的数组中进行排序
  2. When you have all items for sorting, you sort this array当您拥有所有要排序的项目时,您对这个数组进行排序
  3. Then you can loop through this sorted array to process the results, eg display them.然后你可以遍历这个排序的数组来处理结果,例如显示它们。

See the code below - the steps are commented so you can see what you need to do:请参阅下面的代码 - 步骤已注释,因此您可以查看需要执行的操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM