Skip to content
Advertisement

Php Loop TD if rows didn’t exist or match

i want to loop some DTR values and their absent in PHP

1

As you can see the date should be 1,2,3,4,5 but since the only record they have is 3,4,5 there’s some skipped rows, is it possible to loop empty TD and put missing date if there’s no row exist? like i want to loop 1-31 then match the date then put the date where it belongs? idk dude

this is my code for my loop which basically just call the results of my query

              <?php foreach ($report_stmt as $row): ?>

                 <tr>
                  <td><?php 
                   $thisDate = $row['dtr_date'];
                   $day = strtotime($thisDate);
                   $newFormat = ltrim(date('d',$day),0);
                  echo $newFormat;     
                  ?></td>
                  <td><?php echo $row['dtr_in'] ?></td>
                  <td><?php echo $row['dtr_out'] ?></td>
                  <td><?php echo $row['dtr_in2'] ?></td>
                  <td><?php echo $row['dtr_out2'] ?></td>
                </tr> 
             
                <?php endforeach; ?>
 </tbody>

this is my query

$report_list = "SELECT * FROM tbl_dtr INNER JOIN tbl_users_info ON tbl_dtr.dtr_by = tbl_users_info.user_info_email WHERE dtr_by = :user AND dtr_date LIKE '%$month_filter%' ";

Advertisement

Answer

You can try to aggregate an array with the day of month as index. Then just loop through the day of months instead of loop through the query results.

Note: date with ‘j’ is better than trimming leading zero with ‘d’. You may read the DateTime::format for the details of all formatting character.

<?php

// Aggregate an array of reports first
// Note: assume there is no 2 rows with the same 'dtr_date'
$reports = [];
foreach ($report_stmt as $row) {
  $row['date'] = date('j', strtotime($row['dtr_date']));
  $reports[$row['date']] = $row;
}

?>

<?php for ($i=1; $i<=31; $i++): ?>
<tr>
  <td><?php echo $i ?></td>
  <td><?php echo $reports[$i]['dtr_in'] ?? '' ?></td>
  <td><?php echo $reports[$i]['dtr_out'] ?? '' ?></td>
  <td><?php echo $reports[$i]['dtr_in2'] ?? '' ?></td>
  <td><?php echo $reports[$i]['dtr_out2'] ?? '' ?></td>
</tr> 
<?php endfor; ?>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement