2013-12-16 68 views
1

我已经得到了我的网站上活动的阵列看起来像这样:排序PHP在数值上与确定最接近迄今为止

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之前对数组进行排序以便它们以正确的日期顺序显示。

此外,我试图确定哪一个事件最接近实际日期,因为我使用的是轮播类型系统,需要知道哪个显示第一个。

我已经研究过usort,无法自行解决,谢谢你对这些的帮助!

+1

所以,只要将其重新排列为“20131212”并进行比较。对任何人来说,这看起来都不是一件简单的事情吗? – zerkms

+4

'1212013'?那是2013年1月12日? 12月1日? 2013年第121天?在开始排序之前,您应该确定日期表示的含义较少。 –

+2

这个数组来自哪里...即时猜测数据库?如果是这样,为什么不在那里进行排序? – cmorrissey

回答

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) 编辑为清楚起见

+0

这绝对让我在正确的方向!发布最终代码 – MistahMe