我的网站上有一个事件数组,如下所示:
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之前的数组进行排序,以便它们以正确的日期顺序显示。
此外,我正在尝试确定哪一个事件最接近实际日期,因为我正在使用需要知道首先显示哪个的轮播类型系统。
我已经研究过了,我无法自行解决问题,感谢您对这些问题的任何帮助!
答案 0 :(得分:0)
使用此功能: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行称为Ternary) 为清晰起见而编辑