To sort two-dimensional arrays in PHP, you can use the PHP built-in function uasort()
[Use user-defined comparison function to sort values in array and maintain index association]
The callback function is as follows: Note that when the return value of the callback function is a negative number or false, it means that the first parameter of the callback function comes first and the second parameter is arranged last
$person = array( array('num'=>'001','id'=>6,'name'=>'zhangsan','age'=>21), array('num'=>'001','id'=>7,'name'=>'ahangsan','age'=>23), array('num'=>'003','id'=>1,'name'=>'bhangsan','age'=>23), array('num'=>'001','id'=>3,'name'=>'dhangsan','age'=>23), );
//负数或者false表示第一个参数应该在前 function sort_by_name($x,$y){ return strcasecmp($x['name'],$y['name']); }
uasort($person,'sort_by_name');
The following is a two-dimensional array sorting method for reference and interview use:
//$array 要排序的数组 //$row 排序依据列 //$type 排序类型[asc or desc] //return 排好序的数组 function array_sort($array,$row,$type){ $array_temp = array(); foreach($array as $v){ $array_temp[$v[$row]] = $v; } if($type == 'asc'){ ksort($array_temp); }elseif($type='desc'){ krsort($array_temp); }else{ } return $array_temp; }
================================================== ======================
Here are some functions of PHP sorting by the way
[sort sorting arrays] is generally applicable to one-dimensional index arrays and will not maintain the index
[rsort sorts the array in reverse order] The usage is the same as sort
[asort sorts the array and maintains the index relationship] Sorts the values, generally suitable for one-dimensional arrays, maintaining the index relationship
[arsort sorts the array in reverse and maintains the index relationship] is consistent with the usage of asort
[ksort sorts the array by key name]
[krsort sorts the array in reverse order by key name]
================================================== ======================