对二维数组中的 age和name 项排序,name相同的按照age排序。
需要用到PHP的内置函数 array_multisort()
$arr = array(
0 =>array(‘name‘ => ‘godlike‘,‘age‘ => 18),
1=>array(‘name‘ => ‘caomei‘,‘age‘ =>19),
2=>array(‘name‘ => ‘caomei‘,‘age‘ =>20),
)
foreach($arr as $key =>$val){
$num1[$key] = $val[‘name‘];
$num2[$key] = $val[‘age‘];
}
array_multisort($num1,SORT_ASC,$num2,SORT_DESC,$arr);
//根据name升序排序,name相同的根据age降序排序
输出$arr 结果:
Array (
[0] => Array ( [name] => caomei [age] => 20 )
[1] => Array ( [name] => caomei [age] => 19 )
[2] => Array ( [name] => godlike [age] => 18 )
)
时间: 2024-10-13 18:47:01