Accessing an array of keys using uasort in PHP

If PHP has a pretty basic uasort function that looks like this:

 uasort($arr, function($a, $b) { if ($a > $b) return -1; if ($a < $b) return 1; ... } 

The array I'm trying to sort looks like this:

 {[1642] => 1, [9314] => 4, [1634] => 3 ...} 

It contains integers, which are my main comparison criteria. However, if the integers are equal, then I would like to access their key values โ€‹โ€‹inside the uasort function and do some magic with it to figure out the sorting from there.

I donโ€™t know how to do this, since it seems that the variables $a and $b that are passed to the function are integers without corresponding keys, but there should also be a way to access the key because I use the function to actually save the keys . Any ideas?

+7
sorting arrays php usort
source share
2 answers
 uksort($arr, function ($a, $b) use ($arr) { return $arr[$a] - $arr[$b] ?: $a - $b; }); 

You can get the values โ€‹โ€‹with the keys, so use uksort , which gives you the keys. Replace $a - $b with the appropriate magic, here it is simply sorted by key value.

+10
source share

The use directive (in the deceze solution) does not work in my old installation of PHP 5.3.1, while this will provide the result:

 $arr=array('1642'=>1,'9314'=>2,'1634'=>1,'1633'=>5,'1636'=>7,'1610'=>1); print_r($arr); function mycmp($a, $b) { if ($a > $b) return -1; if ($a < $b) return 1; else return 0; } function mysrt($arr){ foreach ($arr as $k => $v) $new[$k]="$v $k"; uasort($new, 'mycmp'); $ret=array(); foreach ($new as $k => $v) $ret[$k]=$arr[$k]; return $ret; } print_r(mysrt($arr)); 

mysrt() does not sort in-place, but returns a sorted array. And, of course, my โ€œmagicโ€ when sorting keys is pretty simple. Keys are sorted in the same way as values. By changing the instruction $new[$k]="$v $k"; , you can change the behavior to suit your needs.

as a note ...

The deceze solution will only work on my server when I use use(&$arr) instead of use($arr) :

 uksort($arr, function ($a, $b) use(&$arr) { return $arr[$a] - $arr[$b] ? $arr[$a] - $arr[$b] : $a - $b; }); 
0
source share

All Articles