Home >Backend Development >PHP Tutorial >How to maintain key names in sorted array using PHP?
To maintain the key names of the sorted array, you can use the following method: use ksort() and krsort() to sort by key and maintain the key order. Use array_multisort() to sort based on multiple columns (including keys) simultaneously. Define custom comparator functions to control collation.
#How to maintain key names in a sorted array using PHP?
Sometimes, after sorting an array in PHP, you want to maintain the original key names. Here's how to do it:
Using the ksort()
and krsort()
functions
ksort ()
and krsort()
sort arrays by key. These functions maintain key names in ascending and descending order respectively:
// 按键升序排序 $array = ['name' => 'John', 'age' => 30, 'city' => 'New York']; ksort($array); // 按键降序排序 $array = ['name' => 'John', 'age' => 30, 'city' => 'New York']; krsort($array);
Using array_multisort()
Function
array_multisort()
Multiple array columns can be sorted at the same time, including keys:
// 按键升序排序,如果键相等则按值降序排序 $names = ['name1', 'name3', 'name5', 'name2', 'name4']; $ages = [20, 30, 50, 40, 60]; array_multisort($names, SORT_ASC, SORT_NUMERIC, $ages, SORT_DESC);
Using a custom comparator
You can define your own comparator function to control the sorting rules , including keys:
function compareKeys($a, $b) { return strcmp($a['key'], $b['key']); } $array = [{'key' => 'a'}, {'key' => 'c'}, {'key' => 'b'}]; usort($array, 'compareKeys');
Practical case: Sorting users by key
// 获取用户数据 $users = [ ['id' => 1, 'name' => 'John Doe'], ['id' => 3, 'name' => 'Jane Smith'], ['id' => 2, 'name' => 'Bob Johnson'] ]; // 使用 ksort 按键升序排序用户 ksort($users); // 按升序的键输出用户列表 foreach ($users as $user) { echo $user['id'] . ': ' . $user['name'] . '<br>'; }
This code will output a user list sorted by id in ascending order, retaining the original key names .
The above is the detailed content of How to maintain key names in sorted array using PHP?. For more information, please follow other related articles on the PHP Chinese website!