2012-10-26 81 views
-1

我有日期陣列這樣檢查日期陣列中的日期,並安排它

$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012-10-20'); 

現在,如果我有一個CURRENT_DATE說

$current_date = '2010-10-11'; 

我如何才能找到什麼最接近過去的日期對此。在這種情況下將是2012年10月7日

感謝

+0

「$ dates」數組中的最後一個值的格式是否爲預期值? – Bjoern

+0

是一個錯字。改變它 – Autolycus

+0

爲什麼最接近'2010-10-11'的值是'2012-10-07'?難道不是「2012-10-02」嗎? – Bjoern

回答

1

嘗試這樣

$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012-10-20'); 

echo "<pre>"; 
print_r($dates); 
$dateArray=array(); 

foreach($dates as $row) 
$dateArray[] = date('Y-m-d', strtotime($row)); 

$current_date = date('Y-m-d', strtotime('2012-10-11')); 
array_push($dateArray,$current_date); 

sort($dateArray); 

echo "<br />"; 
print_r($dateArray); 
echo "</pre>"; 

echo "<br />"; 

$cd_index= array_search($current_date, $dateArray); 

if($cd_index>0) 
{ 
    $pastdate=$dateArray[$cd_index-1]; 
    echo "Pastarray-".$pastdate; 
} 
else 
echo "No Past Date"; 

對於未來日期:

if($cd_index<(count($dateArray)-1)) 
{ 
    $pastdate=$dateArray[$cd_index+1]; 
    echo "Pastarray-".$pastdate; 
} 
else 
echo "No Future Date"; 
+0

如果我想檢查最近的未來日期,該怎麼辦?我會在這裏改變什麼?謝謝 – Autolycus

+0

我在相同的答案更新.. –

1
$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012,10,20'); 
$current_date = '2010-10-11'; 

if(!array_search($current_date, $dates)) 
    array_push($dates, $current_date); 

usort($dates, function($a1, $a2) { 
    return strtotime($a1) - strtotime($a2); 
}); 

$my_current_date_index = array_search($current_date, $dates); 

$my_previous_date = $my_current_date_index == 0 ? 'There is no previous date' : $dates[$my_current_date_index - 1]; 
+0

如果2010-10-11實際上在數組中,這不是唯一的工作嗎? – Corbin

+0

我已經更改了代碼,謝謝 –

0

這也可以使用過..

<?php 
$dates = array('2012-10-07','2012-10-02','2012-10-03', '2012,10,20'); 
$current_date = date('2010-10-11'); 
$closest=''; 
foreach($dates as $d) 
{ 
if(date('y-m-d',strtotime($d))<$current_date && $d>$closest) 
{ 
$closest=$d; 

} 

} 
echo $closest; 
0

我的解決辦法:

// your test data 
$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012-10-20'); 
$current_date = '2012-10-11'; 

// array to help analyzing the file 
$myResolver = array(); 

// processing the array and calculating the unixtimestamp-differences 
array_walk($dates,'calc_ts', array(&$myResolver, $current_date)); 

// sorting the array 
asort($myResolver); 

// fetching the first (aka smallest) value 
$closest = key($myResolver); 

var_dump($closest); 

// calculating the unixtimestam-differences  
function calc_ts($item, $index, $d) { 
    $d[0][$item] = abs(strtotime($item) - strtotime($d[1])); 
} 

作品都與之前和您所需的日期之後的日期。