I have this array:
"Month" => array:4 [ "Week 1" => array:1 [ "Monday" => 1 ] "Week 2" => array:3 [ "Tuesday" => 69 "Wednesday" => 17 "Friday" => 3 ] "Week 3" => array:1 [ "Thursday" => 3 ] "Week 4" => array:2 [ "Monday" => 15 "Friday" => 24 ] ]
But I need to display the result as follow:
| Week | Monday | Tuesday | Wednesday | Thursday | Friday | |--------|--------|---------|-----------|----------|--------| | Week 1 | 1 | 0 | 0 | 0 | 0 | | Week 2 | 0 | 69 | 17 | 0 | 3 | | Week 3 | 0 | 0 | 0 | 3 | 0 | | Week 4 | 15 | 0 | 0 | 0 | 24 |
I have tried the following but it’s showing results for more than 5 days in each week
<table> <tr> foreach ($weeks as $key => $weekcount) { if($key == "Monday"){ <td><?php $weekcount ?></td> } elseif($key == "Tuesday"){ <td><?php $weekcount ?></td> } elseif($key == "Wednesday"){ <td><?php $weekcount ?></td> } elseif($key == "Thursday"){ <td><?php $weekcount ?></td>} elseif($key == "Friday"){ <td><?php $weekcount ?></td> } else {<td><?php $weekcount ?></td>} } </tr> </table>
Thanks in advance for your valuable contributions
Advertisement
Answer
You should check if the given day (key) exists in the array if it is not you should write 0 to the table.
Here is a sample code:
<?php $data = [ 'Month' => [ 'Week1' => [ 'Monday' => 1 ], 'Week2' => [ 'Tuesday' => 69, 'Wednesday' => 17, 'Friday' => 3 ], 'Week3' => [ 'Thursday' => 3 ], 'Week4' => [ 'Monday' => 15, 'Friday' => 24 ] ] ]; $weeks = $data['Month']; ?> <table> <tr> <th>Week</th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> </tr> <?php $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; ?> <?php foreach ($weeks as $key => $week) { ?> <tr> <td><?php echo $key; ?></td> <?php foreach ($days as $day) { ?> <td><?php if (array_key_exists($day, $week)) { echo $week[$day]; } else { echo '0'; } ?></td> <?php } ?> <tr> <?php } ?> </table>
I hope I could help you!