How to sort the 2D array in PHP


Two dimensional array based on the internal array field value can be sorted using the below PHP function.

The Raw/input Array

Below is an array we want to sort it on the base of the array element 'score'.

Array ( [0] => Array ( [id] => 265 [name] => Charleston Soko [score] => 13 ) [1] => Array ( [id] => 241 [name] => Clark M Falcione Jr [score] => 99 ) [2] => Array ( [id] => 242 [name] => Saddam [score] => 44 ) )

PHP function to sort the Array

Below PHP function will change the order of the array. Then you can fetch the array using for, while , foreach loop etc.

uasort($array,function($a, $b){ if($a['score']==$b['score']) return 0; return $a['score'] < $b['score']?1:-1; });

Output of PHP 2D sort array

Array ( [0] => Array ( [id] => 241 [name] => Clark M Falcione Jr [score] => 99 ) [1] => Array ( [id] => 242 [name] => Saddam [score] => 44 ) [2] => Array ( [id] => 265 [name] => Charleston Soko [score] => 13 ) )
Chapter Next »