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 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计