Home  >  Article  >  Backend Development  >  How to sort array keys according to their length in PHP and keep the keys?

How to sort array keys according to their length in PHP and keep the keys?

王林
王林Original
2024-05-02 13:03:02981browse

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.

PHP 中如何根据数组键名长度进行排序,保留键名?

How to sort a PHP array based on the length of the array key (preserving the key)

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:

  • If the key lengths are equal, uksort( ) Functions will maintain their original order.
  • If you need to sort in descending order, you can swap the subtraction operators (- 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn