简体   繁体   中英

Comparing dates after a foreach php array

I'm attempting to add a statement for the 8th of every month, I have compared the dates numerous ways but can't get it to state next to the proper date.

<?php
$month_arr = Array( 
            'July' => Array('num_dates'=>0, 'dates'=>Array()), 
            'August' => Array('num_dates'=>0, 'dates'=>Array()), 
            'September' => Array('num_dates'=>0, 'dates'=>Array()), 
            'October' => Array('num_dates'=>0, 'dates'=>Array()), 
            'November' => Array('num_dates'=>0, 'dates'=>Array()), 
            'December' => Array('num_dates'=>0, 'dates'=>Array()),
            'January' => Array('num_dates'=>0, 'dates'=>Array()) , 
            'February' => Array('num_dates'=>0, 'dates'=>Array()), 
            'March' => Array('num_dates'=>0, 'dates'=>Array()), 
            'April' => Array('num_dates'=>0, 'dates'=>Array()), 
            'May' => Array('num_dates'=>0, 'dates'=>Array()), 
            'June' => Array('num_dates'=>0, 'dates'=>Array())
        );
 $date_arr = Array();

 $date_start = '07/19/2013';
 $date_arr[] = date('M j, Y', strtotime($date_start));


for ($i=1; $i<=4; $i++){
    $date_temp = date('M j, Y', strtotime($date_arr[$i-1] . " + 14 day"));
    $month = date('F', strtotime($date_temp));

    $month_arr[$month]['dates'][] = $date_temp;
    $month_arr[$month]['num_dates'] += 1;
    $date_arr[] = $date_temp;
}

foreach ($month_arr as $k => $v){
    if (!empty($v)){
        if ($v['num_dates'] != 0){
            echo "<BR><BR>Month: " . $k;
            echo "<BR>No. of dates: " . $v['num_dates'];
            foreach ($v['dates'] as $k1=>$v1){
                 echo "<BR>" .$v1;
              $event = 'Aug 8, 2013';
            if($event>$v && !($event<$v1)) {
            echo "Event belongs here on $v1";
              }
            else {
            echo "Event does not belongs here it's to late on the on $v1";
              }
            }
        }
     }  
}

?>

The print will Aug 2, 2013 / Aug 16, 2013 / Aug 30, 2013 / Sep 13, 2013. I want it to go next to Aug 2 2013 as the rest of the dates are too late.

You have a typo in the following. It should be $v1 instead of $v :

$event = 'Aug 8, 2013';
if($event>$v && !($event<$v1)) {
    echo "Event belongs here on $v1";
}else {
    echo "Event does not belongs here it's to late on the on $v1";
}

Also, you are comparing string values. You need to convert them to something that you can compare such as timestamps:

$event = strtotime('Aug 8, 2013');
$vts = strtotime($v1);
if($event > $vts) {
    echo "Event belongs here on $v1";
}else {
    echo "Event does not belongs here it's to late on the on $v1";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM