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

报告相同问题?