可以使用array_multisort()
函數來根據某個字段對二維數組進行排序。
假設有以下二維數組:
$users = array(
array('name' => 'John', 'age' => 25, 'city' => 'New York'),
array('name' => 'Amy', 'age' => 30, 'city' => 'Los Angeles'),
array('name' => 'Peter', 'age' => 20, 'city' => 'Chicago')
);
如果要根據age
字段對數組進行升序排序,可以使用以下代碼:
$ages = array_column($users, 'age'); // 提取所有用戶的age字段值
array_multisort($ages, SORT_ASC, $users); // 根據age字段值進行排序
print_r($users);
輸出結果為:
Array
(
[0] => Array
(
[name] => Peter
[age] => 20
[city] => Chicago
)
[1] => Array
(
[name] => John
[age] => 25
[city] => New York
)
[2] => Array
(
[name] => Amy
[age] => 30
[city] => Los Angeles
)
)
如果要根據city
字段對數組進行降序排序,可以使用以下代碼:
$cities = array_column($users, 'city'); // 提取所有用戶的city字段值
array_multisort($cities, SORT_DESC, $users); // 根據city字段值進行排序
print_r($users);
輸出結果為:
Array
(
[0] => Array
(
[name] => Amy
[age] => 30
[city] => Los Angeles
)
[1] => Array
(
[name] => Peter
[age] => 20
[city] => Chicago
)
[2] => Array
(
[name] => John
[age] => 25
[city] => New York
)
)