How to sort an array of times chronologically?

前端 未结 8 926
梦毁少年i
梦毁少年i 2021-01-17 18:39

I have a non-associative array where the data that comes in is not sorted (I\'m receiving the data from an outside system and cannot force it to come into the array in sorte

8条回答
  •  梦毁少年i
    2021-01-17 19:33

    So, it looks like you're looking for something a little more advanced than a standard sort.

    // WARNING: THIS IS *NOT* BY REFERENCE. IT RETURNS A NEW ARRAY.
    function getSortedTimes(array $group)
    {
        $tmp = array();
        foreach( $group as $times )
        {
            // Basically, I am pairing the string for the start time with 
            // a numeric value.
            $tmp[$times] = strtotime(substr($times, 0, strpos($times, '-')));
        }
        // asort is like sort, but it keeps the pairings just created.
        asort($tmp);
        // the keys of $tmp now refer to your original times.
        return array_keys($tmp);
    }
    

提交回复
热议问题