Current Location: Home> Latest Articles> How to avoid reordering the same keys when using uksort

How to avoid reordering the same keys when using uksort

gitbox 2025-05-31

1. Introduction to uksort() function

uksort(array &$array, callable $callback): The bool function sorts the keys of an array. $callback is a user-defined comparison function that accepts two key names as parameters, returns values ​​less than, equal to or greater than zero, and determines the sorting order.

Sample code:

 $array = [
    'apple' => 1,
    'banana' => 2,
    'cherry' => 3,
];

uksort($array, function($a, $b) {
    return strcmp($a, $b);
});

print_r($array);

Output:

 Array
(
    [apple] => 1
    [banana] => 2
    [cherry] => 3
)

2. Problem description: Repeated sorting caused by the same key

When the key has undergone some kind of preprocessing or mapping, different original keys may be considered "same keys". At this time, the comparison function may be called frequently and repeatedly, affecting performance. For example:

 $array = [
    'a_1' => 10,
    'a_2' => 20,
    'b_1' => 30,
];

uksort($array, function($key1, $key2) {
    // Only compare the part before the underline
    $part1 = explode('_', $key1)[0];
    $part2 = explode('_', $key2)[0];
    return strcmp($part1, $part2);
});

At this point, 'a_1' and 'a_2' are treated as "same keys", and the comparison function may compare them multiple times. For large arrays, this repetition significantly reduces efficiency.

3. The core idea of ​​avoiding repeated sorting

To avoid repeated sorting, the key is to reduce repeated calculations of the same "logical keys" in the comparison function , and even avoid unnecessary comparisons of equivalent keys . Common practices are:

  1. Cache mapping results : The comparison function uses static cache internally to avoid repeated calculation of key mapping values.

  2. First, preprocess and deduplication of the keys : create a mapping table, classify the keys, and compare them directly with the mapping results when sorting.

  3. Use auxiliary array sorting : Use mapped values ​​as auxiliary keys to form a set of mapped values, and then use array_multisort() or other sorting functions to avoid repeated calls.

4. Specific implementation examples

Solution 1: Comparison of cache maps within functions

 $array = [
    'a_1' => 10,
    'a_2' => 20,
    'b_1' => 30,
    'b_2' => 40,
    'c_1' => 50,
];

uksort($array, function($key1, $key2) {
    static $cache = [];

    if (!isset($cache[$key1])) {
        $cache[$key1] = explode('_', $key1)[0];
    }
    if (!isset($cache[$key2])) {
        $cache[$key2] = explode('_', $key2)[0];
    }

    return strcmp($cache[$key1], $cache[$key2]);
});

print_r($array);

In this way, the exploit('_', $key) operation is only performed once, avoiding repeated calculations and improving performance.

Solution 2: Preprocessing mapping keys, assisting sorting

 $array = [
    'a_1' => 10,
    'a_2' => 20,
    'b_1' => 30,
    'b_2' => 40,
    'c_1' => 50,
];

// Generate an array of map keys
$mappedKeys = [];
foreach (array_keys($array) as $key) {
    $mappedKeys[$key] = explode('_', $key)[0];
}

// Sort the key names by mapping key
uasort($mappedKeys, function($a, $b) {
    return strcmp($a, $b);
});

// Reconstruct the main array according to the sorted mapping key
$newArray = [];
foreach ($mappedKeys as $originalKey => $_) {
    $newArray[$originalKey] = $array[$originalKey];
}

print_r($newArray);

This solution avoids multiple calls to compare functions in uksort , and is suitable for use when mapping rules are complex.


5. Summary

  • When using uksort() , the comparison function will be called many times, especially when the keys need to be converted or classified equally, which is prone to repeated calculations.

  • By using caches in comparison functions, or mapping keys in advance, repeated sorting can be effectively avoided and performance and code clarity can be improved.

  • Which solution to choose depends on the array size, mapping rule complexity, and performance requirements.

After mastering the above skills, you can use uksort() to sort complex keys more flexibly and efficiently.