简体   繁体   中英

How to make if statement based on dates from timestamp result in php table?

I'm building a logbook where there will be several entries each day. When I view the logbook I would like to have a small empty space between each date.

Is there an easy way to compare the dates in my first column to then make an if statement when the date changes? In pseudocode: If date in column 1 changes: add empty space.

This is an extract from the code for my table:

    echo "<tr><td>"; 
    echo date('d.m.y', strtotime($row['timestamp']));
    echo "</td><td>";   
    echo date('G:i', strtotime($row['timestamp']));
    echo "</td><td>";    
    echo $row['value'];
    echo "</td></tr>";

Current output:

    Date:       Time:  Value:
    01.01.2017  06:00  40
    01.01.2017  08:00  35
    01.01.2017  10:00  32
    02.01.2017  06:00  57
    02.01.2017  08:00  42
    ...

Wanted output:

    Date:       Time:  Value:
    01.01.2017  06:00  40
    01.01.2017  08:00  35
    01.01.2017  10:00  32

    02.01.2017  06:00  57
    02.01.2017  08:00  42
    ...

Store the $row['timestamp'] in a variable at the end of your foreach loop as eg $previousday. Then you can compare the $row['timestamp'] of the next loop with the $previousday. If they're the not the same, you output an extra otherwise, skip the extra

There will be some kind of loop around your code. In this code you can create a variable $oldDate (or name it however you want it) - and then add the space if it differes from the new data.

// outside of loop
$oldDate = '';

// loop starts here - fills $row somehow
    $curDate = date('d.m.y', strtotime($row['timestamp']));
    if (!empty($oldDate)) {
      if ($oldDate != $curDate) {
         echo 'Some space here';
      }
    }
    $oldDate = $curDate;
   // now add your code

I assume that you are printing your rows in a loop, so you can add variable which will be holding previous date and then check if it's different. I think that you can even skip comparing dates and compare only string value.

$previousDate = '';
foreach ($rows as $row) {
    // your block of echos
    $currentDate = strtotime($row['timestamp']);
    if (!empty($previousDate) && ($previousDate != $currentDate)) {
        echo '<tr><td colspan="3"></td></tr>';
    }
    $previousDate = $currentDate;
}

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