php中二维数组重新排序
public function demo() {
$array = array(
0 => array('id' => '4', 'name' => 'Li', 'age' => '35'),
1 => array('id' => '1', 'name' => 'wang', 'age' => '53'),
2 => array('id' => '3', 'name' => 'meng', 'age' => '50')
);
print_r('原始数组:');
dump($array);
$test = array('id' => '5', 'name' => 'qin', 'age' => '80');
array_push($array, $test); //向二维数组中增加一个元素
print_r('新增元素后数组:');
dump($array);
$array = $this->arraySequence($array); //排序
print_r('重新排序后数组:');
dump($array);
}
/**
* 数组重新排序
* $array 要排序的数组
* $field 排序字段
* $sort 排序方式 SORT_DESC 降序;SORT_ASC 升序
* */
public function arraySequence($array, $field = 'age', $sort = 'SORT_DESC') {
$arr = array();
foreach ($array as $key => $value) {
foreach ($value as $k => $val) {
$arr[$k][$key] = $val;
}
}
array_multisort($arr[$field], constant($sort), $array);
return $array;
}
结果:
原始数组:
array (size=3)新增元素后数组:
0 =>
array (size=3)
'id' => string '4' (length=1)
'name' => string 'Li' (length=2)
'age' => string '35' (length=2)
1 =>
array (size=3)
'id' => string '1' (length=1)
'name' => string 'wang' (length=4)
'age' => string '53' (length=2)
2 =>
array (size=3)
'id' => string '3' (length=1)
'name' => string 'meng' (length=4)
'age' => string '50' (length=2)
array (size=4)重新排序后数组:
0 =>
array (size=3)
'id' => string '4' (length=1)
'name' => string 'Li' (length=2)
'age' => string '35' (length=2)
1 =>
array (size=3)
'id' => string '1' (length=1)
'name' => string 'wang' (length=4)
'age' => string '53' (length=2)
2 =>
array (size=3)
'id' => string '3' (length=1)
'name' => string 'meng' (length=4)
'age' => string '50' (length=2)
3 =>
array (size=3)
'id' => string '5' (length=1)
'name' => string 'qin' (length=3)
'age' => string '80' (length=2)
array (size=4)
0 =>
array (size=3)
'id' => string '5' (length=1)
'name' => string 'qin' (length=3)
'age' => string '80' (length=2)
1 =>
array (size=3)
'id' => string '1' (length=1)
'name' => string 'wang' (length=4)
'age' => string '53' (length=2)
2 =>
array (size=3)
'id' => string '3' (length=1)
'name' => string 'meng' (length=4)
'age' => string '50' (length=2)
3 =>
array (size=3)
'id' => string '4' (length=1)
'name' => string 'Li' (length=2)
'age' => string '35' (length=2)