Through the uksort() function and the custom comparison function compareKeyLengths, PHP arrays can be sorted according to the length of the array key names while retaining the key names. The comparison function calculates the difference in key lengths and returns an integer according to which uksort() sorts the array. In addition, a practical case demonstrates how to sort records from the database by field name length.
In PHP, you can use uksort()
The function sorts the array according to the length of the array key name. This function accepts a callback function as a parameter, which compares two key names and returns an integer representing the difference in key length.
Sort code:
<?php function compareKeyLengths(string $key1, string $key2): int { return strlen($key1) - strlen($key2); } $array = ['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3']; uksort($array, 'compareKeyLengths'); print_r($array);
Output:
Array ( [key1] => value1 [key2] => value2 [key3] => value3 )
As you can see, the array has been sorted based on key length , while retaining the key names.
Practical case:
This is an example of sorting records from the database by the length of the field name.
<?php $records = [ ['firstName' => 'John', 'lastName' => 'Doe'], ['firstName' => 'Jane', 'lastName' => 'Smith'], ['firstName' => 'Bob', 'lastName' => 'Johnson'], ]; uksort($records, 'compareKeyLengths'); foreach ($records as $record) { echo 'Name: ' . $record['firstName'] . ' ' . $record['lastName'] . PHP_EOL; }
Output:
Name: Bob Johnson Name: Jane Smith Name: John Doe
Note:
uksort( )
Functions will maintain their original order. -
and
) in the comparison function. The above is the detailed content of How to sort array keys according to their length in PHP and keep the keys?. For more information, please follow other related articles on the PHP Chinese website!