实现指定多维数组一个字段排序
元数据:
$array = array(
0=>array('id'=>8,'name'=>'Tom'),
1=>array('id'=>9,'name'=>'Peter'),
2=>array('id'=>5,'name'=>'Jack')
);
实现:通过将待排序数组的各个数组的$field保存在一位数组fieldArr中,在传入array_multisort中参与排序。其中field数组的值如下:
array(0=>8,1=>9,2=>5)
function sortArrByOneField(&$array, $field, $desc = false){
$fieldArr = array();
foreach ($array as $k => $v) {
$fieldArr[$k] = $v[$field];
}
$sort = $desc == false ? SORT_ASC : SORT_DESC;
array_multisort($fieldArr, $sort, $array);
}
传入 array_multisort后,相当于对$field一维数组的排序,而后根据排序后的key重新构建传入的待排序数组
结果:
$array = array(
0=>array('id'=>5,'name'=>'Jack')
1=>array('id'=>8,'name'=>'Tom'),
2=>array('id'=>9,'name'=>'Peter')
);
实现多维数组的指定两个字段排序
$arr = array(
'0' => array(
'id' => 3,
'age' => 27
),
'1' => array(
'id' => 5,
'age' => 50
),
'2' => array(
'id' => 4,
'age' => 44
),
'3' => array(
'id' => 3,
'age' => 78
)
);
foreach ( $arr as $key => $row ){
$id[$key] = $row ['id'];
$age[$key] = $row ['age'];
}
array_multisort($id, SORT_ASC, $age, SORT_DESC, $arr);
print_r($arr);
/*result:
Array(
[0]=>Array(['id']=>3 ['age']=>78)
[1]=>Array(['id']=>3 ['age']=>27)
[2]=>Array(['id']=>4 ['age']=>44)
[3]=>Array(['id']=>5 ['age']=>50)
)
*/
实现多维数组的指定多个字段排序
重构上述代码,只要采用php中的func_get_args函数,来动态获取传入的值,既可以解决多字段个数不确定的问题。实现如下:
$array1 = array(
0=>array('id'=>8,'name'=>'Apple','age'=> 18),
1=>array('id'=>8,'name'=>'Bed','age'=>17),
2=>array('id'=>5,'name'=>'Cos','age'=>16),
3=>array('id'=>5,'name'=>'Cos','age'=>14)
);
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);
}
$arr = sortArrByManyField($array1,'id',SORT_ASC,'name',SORT_ASC,'age',SORT_DESC);
print_r($arr);
结果:
array(4) {
[0]=>array(3) {
["id"]=>int(5)
["name"]=>string(3) "Cos"
["age"]=>int(16)
}
[1]=>array(3) {
["id"]=>int(5)
["name"]=>string(3) "Cos"
["age"]=>int(14)
}
[2]=>array(3) {
["id"]=>int(8)
["name"]=>string(5) "Apple"
["age"]=>int(18)
}
[3]=>array(3) {
["id"]=>int(8)
["name"]=>string(3) "Bed"
["age"]=>int(17)
}
}
版权声明:本文为github_35634180原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。