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

如何解决使用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,"original_title": "Fear and Desire","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,"poster_path": "/oiN9OUOGbVywUHjto30AfLpnIJ7.jpg","backdrop_path": "/e3o0Dwlzzpd4kJpOOJgVyMstnII.jpg","title": "Fear and Desire","popularity": 6.052,"genre_ids": [
        18,10752
      ],"vote_average": 5.5,"release_date": "1953-04-01","credit_id": "55d0b9c392514131a5007a4c"
    },{
      "id": 45314,"original_title": "The Seafarers","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,"release_date": "1953-10-15","vote_average": 4.7,"title": "The Seafarers","popularity": 3.009,"backdrop_path": null,"poster_path": "/nSucFIAQ5CowEE1WZ87mz3OsbQ1.jpg","credit_id": "55d0cae1c3a36877570014d2"
    },{
      "id": 975,"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,"poster_path": "/peblNaHOiTR8DACYyUWsJHhK6GP.jpg","backdrop_path": "/yFykLiFuBU6CrGWr2hLP0ttbQ2i.jpg","title": "Paths of Glory","popularity": 11.573,"vote_average": 8.3,"release_date": "1957-09-18","credit_id": "5706f1259251412b1400065c"
    },{
      "id": 45970,"original_title": "Flying Padre","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,"release_date": "1951-03-23","vote_average": 5.2,"title": "Flying Padre","popularity": 4.033,"backdrop_path": "/5HisBYhc75h0DYXSMJWN1eFaxse.jpg","poster_path": "/5aog5qVlMFakpogT1Nar9Z7gqq4.jpg","credit_id": "5e94991dccb15f001571103c"
    },{
      "id": 10056,"original_title": "Killer's Kiss","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,"poster_path": "/jc5EjvQywJqS8Xm0RWMoblJvCM6.jpg","backdrop_path": "/6VhN0ScAA8VgK3qyRnZ7azD9XEV.jpg","title": "Killer's Kiss","popularity": 10.353,"genre_ids": [
        80,18,53
      ],"vote_average": 6.4,"release_date": "1955-09-21","credit_id": "5e9499448e87020013ce555f"
    },{
      "id": 185,"department": "Directing","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,"release_date": "1971-12-19","vote_average": 8.2,"title": "A Clockwork Orange","popularity": 25.023,"genre_ids": [
        878,18
      ],"backdrop_path": "/keblhZFIZYiWflmURWNHEuS2jqL.jpg","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完全按照原样从数组传递元素。也就是说,在这种情况下,您的数组包含对象-因此,您需要对对象的属性进行比较,而不要作为数组中的元素进行比较。

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-