0

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!

u_mulder
  • 54,101
  • 5
  • 48
  • 64
infoo
  • 3
  • 1
  • What is meant by `tier`? – u_mulder Jan 21 '17 at 10:38
  • Which array do you want to sort: the outer array, or each of the inner series, or both? And if the outer, by which of the years inside series, should the outer be sorted? By the max, min, avg, sum? – trincot Jan 21 '17 at 10:40
  • Possible duplicate of [How do I Sort a Multidimensional Array in PHP](http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php) – yivi Jan 21 '17 at 10:42
  • By tier, I mean the levels down in the array. I want to sort the inner array that contains the year and estpay data. Thanks. – infoo Jan 23 '17 at 14:12

1 Answers1

0

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'];
});
jonbaldie
  • 378
  • 5
  • 12
  • Thanks. To get this to work, I had to create a new array using $newarray = $array[series], but when I then used this on the new array it worked like a charm. Thanks everyone for their help. – infoo Jan 23 '17 at 14:59