Sorting 2-dimensional array in descending order keeping original indexes
I need to sort 2-dimensional array in descending order keeping original indexes:
$arr = array(); for ($i=0; $i<5; $i++) { $arr[] = array(rand(0,5), rand(10,100)); }
The result must be something like this:
[0] => array(5, 100) [1] => array(5, 90) [2] => array(5, 35) [3] => array(4, 10) [4] => array(3, 15)
So, firstly, the array is sorted with respect to the 1st column, and, secondly it is sorted with respect to the 2nd column.
The function arsort works with vectors, if I understand it correctly.
How can I solve this task?
Answers
see http://docs.php.net/uasort
e.g.
<?php $arr = array( 'A'=>array(5, 100), 'B'=>array(4, 10), 'C'=>array(5, 35), 'D'=>array(3, 15), 'E'=>array(5, 90) ); uasort($arr, function($a, $b) { if ( $a[0] < $b[0] ) return 1; else if ( $a[0] > $b[0] ) return -1; else if ( $a[1] < $b[1] ) return 1; else if ( $a[1] > $b[1] ) return -1; else return 0; }); foreach($arr as $k=>$v) { echo $k,'=', join(', ', $v), "\n"; }
prints
A=5, 100 E=5, 90 C=5, 35 B=4, 10 D=3, 15