对PHP进行数字排序&;确定最接近日期的


Sort PHP Numerically & Identify which is closest to date

我的网站上有一个事件数组,看起来像这样:

array(
    'title' => 'Name',
    'link' => 'http://www.eventssite.com',
    'image' => '_img/event_img.jpg',
    'location' => 'Florida, US',
    'year' => '2013',
    'date' => 'Dec. 12-14',
    'desc' => 'Description about the event.',
    'dateid' => '1212013'
),

我想按照dateid对foreach之前的数组进行排序,以便它们以正确的Date顺序显示。

此外,我正在尝试确定哪一个事件最接近实际日期,因为我使用的是旋转木马类型的系统,需要知道首先显示哪个。

我已经研究过usort,但无法单独使用,感谢您在这些方面的帮助!

使用此函数:http://php.net/usort

例如:

<?php
//just an array of arrays with the date as one of the values of the array
$array = array(
    array(
        'date' => '05/02/1988',
        'name' => 'Jacob'
    ),
    array(
        'date' => '12/12/1968',
        'name' => 'Sherry'
    ),
    array(
        'date' => '05/15/1978',
        'name' => 'Dave'
    )
);
//usort is used for non conventional sorting. 
//which could help in this case
//NOTICE - we are not setting a variable here! 
//so dont call it like $array = usort(...) you will just be setting $array = true
usort($array,'sortFunction');
//display the results
var_dump($array);
//function called by usort
function sortFunction($a,$b){
    //turn the dates into integers to compare them
    //
    $strA = strtotime($a['date']);
    $strB = strtotime($b['date']);
    //don't worry about sorting if they are equal
    if($strA == $strB){
        return 0;
    }
    else{
            //if a is smaller than b, the move it up by one.
        return $strA < $strB ? -1 : 1; 
    }
}
?>

(如果你感兴趣的话,第40行叫做三进制)为清晰而编辑