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'];
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?