PHP 多维数组的排序问题 根据二维数组中某个项排序
程序员文章站
2023-10-17 16:38:56
php内置函数 array_multisort 要求每个数组大小一样 $areas是地区的二维数组,包含人数和次数,现在要按这2种数进行降序排序 复制代码 代码如下: fo...
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
$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
下一篇: 榴莲营养价值,想不到它有这么多好处