Home >Backend Development >PHP Tutorial >Simple implementation method of two-dimensional array sorting in PHP_php skills
The example in this article describes a simple implementation method of two-dimensional array sorting in PHP. Share it with everyone for your reference, the details are as follows:
function multi_compare($a, $b) { $val_arr = array( 'gold'=>'asc', 'silver'=>'desc'//还可以增加额外的排序条件 ); foreach($val_arr as $key => $val){ if($a[$key] == $b[$key]){ continue; } return (($val == 'desc')?-1:1) * (($a[$key] < $b[$key]) ? -1 : 1); } return 0; } $arr = array( array('gold'=>1, 'silver'=>2), array('gold'=>8, 'silver'=>10), array('gold'=>8, 'silver'=>8), array('gold'=>2, 'silver'=>1), ); uasort($arr, 'multi_compare'); print_r($arr);
The running results are as follows:
Array ( [0] => Array ( [gold] => 1 [silver] => 2 ) [3] => Array ( [gold] => 2 [silver] => 1 ) [1] => Array ( [gold] => 8 [silver] => 10 ) [2] => Array ( [gold] => 8 [silver] => 8 ) )
Readers who are interested in more PHP related content can check out the special topics of this site: "php sorting algorithm summary", "PHP basic syntax introductory tutorial", " Summary of PHP error and exception handling methods " and "Summary of common PHP functions and techniques "
I hope this article will be helpful to everyone in PHP programming.