- 相關(guān)推薦
PHP 多維數(shù)組的排序問(wèn)題
PHP 多維數(shù)組排序 根據(jù)二維數(shù)組中某個(gè)項(xiàng)排序,下面是小編給大家分享的PHP 多維數(shù)組的排序問(wèn)題。
PHP 多維數(shù)組排序 根據(jù)二PHP內(nèi)置函數(shù) array_multisort 要求每個(gè)數(shù)組大小一樣
$areas是地區(qū)的二維數(shù)組,包含人數(shù)和次數(shù),現(xiàn)在要按這2種數(shù)進(jìn)行降序排序
代碼如下:
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);
}
比如有個(gè)多為數(shù)組:
代碼如下:
$arr = array(
‘d' => array(‘id' => 5, ‘name' => 1, ‘a(chǎn)ge' => 7),
‘b' => array(‘id' => 2,'name' => 3,'age' => 4),
‘a(chǎn)' => array(‘id' => 8,'name' => 10,'age' => 5),
‘c' => array(‘id' => 1,'name' => 2,'age' => 2)
);
需要對(duì)二維數(shù)組中的 age 項(xiàng)排序。
需要用到PHP的內(nèi)置函數(shù) array_multisort(),可以看手冊(cè)。
自定義函數(shù):
代碼如下:
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 “
”;
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 大宇
維數(shù)組中某個(gè)項(xiàng)排序,需要的朋友可以參考下。
【PHP 多維數(shù)組的排序問(wèn)題】相關(guān)文章:
php遞歸遍歷多維數(shù)組的方法10-06
php對(duì)特殊語(yǔ)句查詢結(jié)果進(jìn)行數(shù)組排序的方法技巧07-01
PHP對(duì)特殊語(yǔ)文查詢結(jié)果進(jìn)行數(shù)組排序的方法介紹09-28
簡(jiǎn)單PHP數(shù)組函數(shù)介紹09-26
PHP超全局?jǐn)?shù)組08-16
PHP數(shù)組面試考題05-17