-1

私はこのような日付配列を持っています

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

今、current_dateと言ったら

$current_date = '2010-10-11';

これに最も近い過去の日付を見つけるにはどうすればよいですか。この場合は 2012-10-07 になります

ありがとう

4

4 に答える 4

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];
于 2012-10-26T05:57:53.080 に答える
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";
于 2012-10-26T06:02:10.630 に答える
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;
于 2012-10-26T06:15:25.100 に答える
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]));
}

希望日の前後の日付の両方で機能します。

于 2012-10-26T07:39:46.237 に答える