0

I looked quite a bit around (like here the array-sort-comparisons), and tried to figure out how to sort (or reverse) my multiple-elements array. But in vain.

I have three elements in my array, and want to sort the it by "year" ASC:

array(52) {
  [0]=>
  array(3) {
    ["id"]=>
    string(2) "SI"
    ["year"]=>
    string(4) "2012"
    ["value"]=>
    string(7) "3711339"
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(2) "SI"
    ["year"]=>
    string(4) "2011"
    ["value"]=>
    string(7) "3810626"
  }
  [2]=>
  array(3) {
    ["id"]=>
    string(2) "SI"
    ["year"]=>
    string(4) "2010"
    ["value"]=>
    string(7) "3714946"
  }

How would that be possible? Somehow one needs to be able to specify which of the three elements is the "key" to be the basis of the sorting.

Thanks for any hints!

luftikus143
  • 1,285
  • 3
  • 27
  • 52

3 Answers3

3

Use usort() with a custom comparison function:

usort($arr, function (array $a, array $b) {
    return $a['year'] - $b['year'];
});

Demo

deceze
  • 510,633
  • 85
  • 743
  • 889
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
3

PHP >= 5.5.0

array_multisort(array_column($array, 'year'), SORT_ASC, $array);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
-1

As you stated reversing will work for your example. you can do it fairly simple

$arr = array(2012, 2011, 2010);
$reversed_arr = array_reverse($arr);
Fabian de Pabian
  • 599
  • 4
  • 20
  • This wouldn't work if the order of the array is different. – Amal Murali Mar 24 '14 at 17:32
  • Totally agree but @luftikus143 mentioned reversing was also an option in his question, and seen the order of his example reversing will work too. But then we should ask ourselves, if the array is ordered by year the wrong way around, can't we tackle this at the source, as in the database query? – Fabian de Pabian Mar 24 '14 at 17:34
  • 1
    Of course. That would be the best way to go. However, if this data is retrieved from an external API which the OP has no control over, then the only solution would be to sort it manually on the PHP-side. If the array is always in reverse order, `array_reverse()` is the best way to go, but if there are more sorting parameters or if the order of the array is slightly different then you'd have to resort to a manual sorting technique. – Amal Murali Mar 24 '14 at 17:37
  • The array has 53 elements, and I find it unlikely that it is in descending order by year, but maybe... – AbraCadaver Mar 24 '14 at 17:38
  • Thanks for all this. Indeed, it's based on an API which spits out the results with years in reversed order. – luftikus143 Mar 24 '14 at 19:10