PHP数组 - 查找最近的日期

时间:2015-04-15 10:10:54

标签: php

使用小公式从存储在数组中的多个日期中查找壁橱日期。我可以使用硬编码日期,但不使用PHP变量,任何想法?

<?php
                $dates = array
                (
                    '0'=> date('Y-m-d', $Date1),
                    '1'=> date('Y-m-d', $Date2),
                    '2'=> date('Y-m-d', $Date3),
                    '3'=> date('Y-m-d', $Date4),
                    '4'=> date('Y-m-d', $Date5),
                    '5'=> date('Y-m-d', $Date6),
                    '6'=> date('Y-m-d', $Date7),
                    '7'=> date('Y-m-d', $Date8)
                );

                function closes($dates, $findate)
                {
                    $newDates = array();

                    foreach($dates as $date)
                    {
                        $newDates[] = strtotime($date);
                    }

                    sort($newDates);
                    foreach ($newDates as $a)
                    {
                        if ($a >= strtotime($findate)) return $a;
                    }
                    return end($newDates);
                }


                $values = closes($dates, date('Y-m-d'));

                ?>
                <h3>Next Date</h3><br/>
                <?php echo date('l, F jS, Y',$values); 

                }?>

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

    <?php
    $day1 = '2015-01-01';
    $day2 = '2015-02-08';
    $day3 = '2015-03-13';
    $day4 = '2015-04-05';
    $day5 = '2015-05-27';
    $day6 = '2015-06-08';
    $day7 = '2015-07-19';  // YOU CAN ASSIGN DATE DYNAMICALLY

    $referenceDate = strtotime(date('Y-m-d')); // REFERENCE DATE TO BE COMPARED


    $dates = array(
                0 => strtotime($day1),
                1 => strtotime($day2),
                2 => strtotime($day3),
                3 => strtotime($day4),
                4 => strtotime($day5),
                5 => strtotime($day6),
                6 => strtotime($day7),
            ); // FORM AN ARRAY 

    foreach($dates as $date) {
        $diff = $date - $referenceDate;

        //echo '<pre>'; print_r($diff);

        if($diff > 0){
            $resultArrFuture[$diff] = date('d-m-Y', $date);
        } else {
            $resultArrPast[$diff] = date('d-m-Y', $date);
        }
    }       
    // THIS WILL GIVE YOU CLOSEST DATE IN TWO DIFFERENT ARRAY ONE IS FOR FUTURE DATE OF REFERENCE ARRAY AND ONE FOR PAST 


    ksort($resultArrFuture);
    krsort($resultArrPast);

    echo '<pre>'; print_r($resultArrFuture);
    echo '<pre>'; print_r($resultArrPast);

?>