开发者

Order array based on relative time (not a time stamp) in PHP?

开发者 https://www.devze.com 2023-02-01 19:50 出处:网络
I have an array of events... each event has a key called \"time\". The \"time\" key stores a string such as开发者_高级运维 \"8:00 AM\" or \"6:00 PM\".

I have an array of events... each event has a key called "time". The "time" key stores a string such as开发者_高级运维 "8:00 AM" or "6:00 PM".

I need to order this array based on that time key. How would this be possible?


strtotime() can parse things like 8:00 AM. It is your friend.

function cmp_func($a, $b) {
    $atime = strtotime($a['time']);
    $btime = strtotime($b['time']);
    if($atime == $btime) return 0;
    return ($atime < $btime) ? -1 : 1;
}

usort($your_array, 'cmp_func');

Note that if the array(s) you're sorting in this fashion are very large, it may be worth it to store the value from strtotime() as part of the array beforehand, to reduce the number of calls to it overall.


php.net sort function, one off the comments

$array[0]['name']  = 'Chris';
$array[0]['phone'] = '3971095';
$array[0]['year']  = '1978';
$array[0]['address'] = 'Street 1';

$array[1]['name']  = 'Breanne';
$array[1]['phone'] = '3766350';
$array[1]['year']  = '1990';
$array[1]['address'] = 'Street 2';

$array[2]['name']  = 'Dusty';
$array[2]['phone'] = '1541120';
$array[2]['year']  = '1982';
$array[2]['address'] = 'Street 3';

function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL, $key5=NULL, $key6=NULL){
    // sort by ?
    foreach ($array as $pos =>  $val)
        $tmp_array[$pos] = $val[$sort_by];
    asort($tmp_array);

    // display however you want
    foreach ($tmp_array as $pos =>  $val){
        $return_array[$pos][$sort_by] = $array[$pos][$sort_by];
        $return_array[$pos][$key1] = $array[$pos][$key1];
        if (isset($key2)){
            $return_array[$pos][$key2] = $array[$pos][$key2];
            }
        if (isset($key3)){
            $return_array[$pos][$key3] = $array[$pos][$key3];
            }
        if (isset($key4)){
            $return_array[$pos][$key4] = $array[$pos][$key4];
            }
        if (isset($key5)){
            $return_array[$pos][$key5] = $array[$pos][$key5];
            }
        if (isset($key6)){
            $return_array[$pos][$key6] = $array[$pos][$key6];
            }
        }
    return $return_array;
    }

//usage (only enter the keys you want sorted):

$sorted = multisort($array,'year','name','phone','address');
print_r($sorted);

//output:
Array ( [0] => Array ( [year] => 1978 [name] => Chris [phone] => 3971095 [address] => Street 1 ) [2] => Array ( [year] => 1982 [name] => Dusty [phone] => 1541120 [address] => Street 3 ) [1] => Array ( [year] => 1990 [name] => Breanne [phone] => 3766350 [address] => Street 2 ) )
0

精彩评论

暂无评论...
验证码 换一张
取 消