如何在PHP中对数组按键升序排序?ksort/uksort无法满足需求
Hey there! I see you've been stuck on sorting your array by its keys for a couple of days—let's get this sorted out (pun intended!). The problem with using plain ksort() here is that it treats your keys as regular strings. So when comparing something like 2020-06-24,13:00 and 2020-06-24,8:30, it looks at the first character after the comma: 1 vs 8. Since 1 comes before 8 lexicographically, 13:00 gets placed ahead of 8:30, which isn't what you want.
The Solution: Use uksort() with a Custom Comparison Function
uksort() lets you define exactly how to compare the keys. We'll split each key into date and time parts, sort first by date, then by time for entries with the same date. Here's the code that will give you your desired output:
// Your original array $yourArray = [ '2020-06-22,13:00' => [1663, 1664], '2020-06-22,14:00' => [1665, 1666], '2020-06-24,13:00' => [1715], '2020-06-24,8:30' => [1714], '2020-06-23,13:00' => [1724], '2020-06-23,8:30' => [1727] ]; // Custom sorting logic uksort($yourArray, function($keyA, $keyB) { // Split each key into date and time components list($dateA, $timeA) = explode(',', $keyA); list($dateB, $timeB) = explode(',', $keyB); // First compare the dates $dateDifference = strtotime($dateA) - strtotime($dateB); if ($dateDifference !== 0) { return $dateDifference; } // If dates are the same, compare the times return strtotime($timeA) - strtotime($timeB); }); // Output the sorted array print_r($yourArray);
How This Works:
- Split Keys: We use
explode(',', $key)to separate the date and time parts of each key. - Date Comparison: Convert the date strings to timestamps with
strtotime()—subtracting these gives us a positive/negative number that tellsuksort()which date comes first. - Time Comparison: If two keys have the same date, we do the same timestamp conversion for the time parts to sort them chronologically.
When you run this code, you'll get exactly the sorted array you're expecting:
Array ( [2020-06-22,13:00] => Array ( [0] => 1663 [1] => 1664 ) [2020-06-22,14:00] => Array ( [0] => 1665 [1] => 1666 ) [2020-06-23,8:30] => Array ( [0] => 1727 ) [2020-06-23,13:00] => Array ( [0] => 1724 ) [2020-06-24,8:30] => Array ( [0] => 1714 ) [2020-06-24,13:00] => Array ( [0] => 1715 ) )
内容的提问来源于stack exchange,提问作者Pawan Dongol




