PHP內置函數 array_multisort 要求每個數組大小一樣
$areas是地區的二維數組,包含人數和次數,現在要按這2種數進行降序排序
復制代碼 代碼如下:
foreach($areaArray as &$areas) {
$times = $numbers = array();
foreach($areas as $province => $v) {
$times[$province] = $v['times'];
$numbers[$province] = $v['numbers'];
}
array_multisort($times, SORT_DESC, $numbers, SORT_DESC, $areas);
}
比如有個多為數組:
復制代碼 代碼如下:
$arr = array(
‘d' => array(‘id' => 5, ‘name' => 1, ‘age' => 7),
‘b' => array(‘id' => 2,'name' => 3,'age' => 4),
‘a' => array(‘id' => 8,'name' => 10,'age' => 5),
‘c' => array(‘id' => 1,'name' => 2,'age' => 2)
);
需要對二維數組中的 age 項排序。
需要用到PHP的內置函數 array_multisort(),可以看手冊。
自定義函數:
復制代碼 代碼如下:
function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
if(is_array($multi_array)){
foreach ($multi_array as $row_array){
if(is_array($row_array)){
$key_array[] = $row_array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_array,$sort,$multi_array);
return $multi_array;
}
//處理
echo “<pre/>”;
print_r(multi_array_sort($arr,'age'));exit;
//輸出
Array
(
[c] => Array
(
[id] => 1
[name] => 2
[age] => 2
)
[b] => Array
(
[id] => 2
[name] => 3
[age] => 4
)
[a] => Array
(
[id] => 8
[name] => 10
[age] => 5
)
[d] => Array
(
[id] => 5
[name] => 1
[age] => 7
)
)
written by 大宇
0