有个用户的二维数组1
2
3
4
5
6
7
8
9
10$arr = [
['id' => 1, 'name' => 'Alexander', 'age' => 26],
['id' => 4, 'name' => 'James', 'age' => 18],
['id' => 3, 'name' => 'David', 'age' => 22],
['id' => 7, 'name' => 'Anthony', 'age' => 25],
['id' => 5, 'name' => 'Emily', 'age' => 18],
['id' => 8, 'name' => 'Elizabeth', 'age' => 23],
['id' => 2, 'name' => 'Lauren', 'age' => 18],
['id' => 6, 'name' => 'Alyssa', 'age' => 17]
];
当需要用户年龄(age)来进行从小到大排序时1
2$sort_column = array_column($arr, 'age');
array_multisort($sort_column, SORT_ASC, $arr);
$arr数组会变成这样1
2
3
4
5
6
7
8
9
10$arr = [
['id' => 6, 'name' => 'Alyssa', 'age' => 17],
['id' => 2, 'name' => 'Lauren', 'age' => 18],
['id' => 4, 'name' => 'James', 'age' => 18],
['id' => 5, 'name' => 'Emily', 'age' => 18],
['id' => 3, 'name' => 'David', 'age' => 22],
['id' => 8, 'name' => 'Elizabeth', 'age' => 23],
['id' => 7, 'name' => 'Anthony', 'age' => 25],
['id' => 1, 'name' => 'Alexander', 'age' => 26],
];
当需要用户年龄(age)来进行从小到大,并且用户编号(id)从大到小排序时1
2
3
4
5foreach ($arr as $key => $value) {
$id_arr[] = $value['id'];
$age_arr[] = $value['age'];
}
array_multisort($age_arr, SORT_ASC, $id_arr, SORT_DESC, $arr);
$arr数组会变成这样1
2
3
4
5
6
7
8
9
10$arr = [
['id' => 6, 'name' => 'Alyssa', 'age' => 17],
['id' => 5, 'name' => 'Emily', 'age' => 18],
['id' => 4, 'name' => 'James', 'age' => 18],
['id' => 2, 'name' => 'Lauren', 'age' => 18],
['id' => 3, 'name' => 'David', 'age' => 22],
['id' => 8, 'name' => 'Elizabeth', 'age' => 23],
['id' => 7, 'name' => 'Anthony', 'age' => 25],
['id' => 1, 'name' => 'Alexander', 'age' => 26],
];
最后更新: 2024年04月12日 02:44