douyi0219 2017-01-21 10:34
浏览 24
已采纳

在PHP中对多层和多维数组进行排序

My first question post here, although I'm a long time user. My PHP skills aren't advanced. I'm using PHP7 BTW.

I've found similar questions to this one, but not with the tier element, and so none of the answers I've tried so far have worked. It's probably obvious to a more experienced PHP programmer.

I've got some data in the json format, and decoded it into the following array:

Array ( 
    [soc] => 3421 
    [series] => Array ( 
            [0] => Array ( [year] => 2013 [estpay] => 620 ) 
            [1] => Array ( [year] => 2015 [estpay] => 580 ) 
    ) 
)

The data source varies, and so some times there are more years data available and sometimes less. It will also change over time as new data is added.

I want to sort the array so that the most recent year is always first. As I mentioned earlier, I've tried a few of the solutions that have been posted on here for multidimensional arrays, but the data I'm using has the multidimensional array in a lower tier of the array, and so I haven't been able to work out how to change the example code for multidimensional arrays to work around this.

As I mentioned, I'm no PHP expert, so please make no assumptions on my skill level in any replies. Thanks for your help!

  • 写回答

1条回答 默认 最新

  • doushi1510 2017-01-21 10:40
    关注

    Assuming you're using PHP7, and as you said you want to order by year descending, then for each array that you want to sort, try the below:

    usort($array, function ($a, $b) {
        return $b['year'] <=> $a['year'];
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵