You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在PHP中对数组按键升序排序?ksort/uksort无法满足需求

Fixing Custom Key Sorting for Your Date-Time Array

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:

  1. Split Keys: We use explode(',', $key) to separate the date and time parts of each key.
  2. Date Comparison: Convert the date strings to timestamps with strtotime()—subtracting these gives us a positive/negative number that tells uksort() which date comes first.
  3. 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

火山引擎 最新活动