主要用到的PHP函数 array_multisort() 1.先实现指定多维数组一个字段排序
根据二维数组的id值来排序,转换后的数组格式如下:
function arraySortByOneField($data, $field, $sort = SORT_DESC) { $field = array_column($data, $field); array_multisort($field,$sort,$data); return $data; }
如:
$data = array(0=>array(\'id\'=>7, \'name\'=>\'Apple\', \'age\'=> 18),1=>array(\'id\'=>8, \'name\'=>\'Bed\', \'age\'=>17),2=>array(\'id\'=>6, \'name\'=>\'Cos\', \'age\'=>16),3=>array(\'id\'=>5, \'name\'=>\'Cos\', \'age\'=>14)); $newArray = arraySortByOneField($data, \'id\', SORT_DESC); var_dump($newArray );
2.实现多维数组的指定两个字段排序
根据二维数组的多个属性值来排序,转换后的数组格式如下:
function sortArrByManyField() { $args = func_get_args(); if(empty($args)){ return null; } $arr = array_shift($args); if(!is_array($arr)){ throw new Exception("第一个参数不为数组"); } foreach($args as $key => $field){ if(is_string($field)){ $temp = array(); foreach($arr as $index=> $val){ $temp[$index] = $val[$field]; } $args[$key] = $temp; } } $args[] = &$arr;//引用值 call_user_func_array(\'array_multisort\',$args); return array_pop($args); }
如:
$data = array(0=>array(\'id\'=>7, \'name\'=>\'Apple\', \'age\'=> 18),1=>array(\'id\'=>8, \'name\'=>\'Bed\', \'age\'=>17),2=>array(\'id\'=>6, \'name\'=>\'Cos\', \'age\'=>16),3=>array(\'id\'=>5, \'name\'=>\'Cos\', \'age\'=>14)); $newArray = arraySortByManyField($data, \'id\', SORT_ASC, \'name\', SORT_ASC, \'age\', SORT_DESC); var_dump($newArray );
请发表评论