Reputation: 867
<?php
?>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>
</th>
<?php
for($i = 1; $i <=31;$i++){
echo '<th>'.$i.'</th>';
}
?>
</tr>
</thead>
<tbody>
<td>
Item A
</td>
<?php
$qty_n_day = '1/2,3/6';
$qty_day = explode(',', $qty_n_day);
foreach ($qty_day as $qd) {
list($qty,$day) = explode('/', $qd);
for($i = 1; $i <=31;$i++){
if($day == $i)
echo '<td>'.$qty.'</td>';
else
echo '<td>-</td>';
}
}
?>
</tbody>
</table>
</body>
</html>
Output result
My expected result
How can i do that? Is my logic wrong?
Upvotes: 1
Views: 63
Reputation: 23675
The problem arises from the fact that you are performing two iterations, the first one processing 2
cycles and the second one processing 31
cycles... for a total of 62
elements being generated.
I propose you a much more compact solution, that builds up the final array first and then simply prints it:
<?php
$arr = array_fill(1, 31, "-");
$qty_n_day = '1/2,3/6';
$qty_day = explode(',', $qty_n_day);
foreach ($qty_day as $qd)
{
list($qty,$day) = explode('/', $qd);
$arr[$day] = $qty;
}
for ($i = 1; $i <= 31; ++$i)
{
echo '<td>'.$arr[$i].'</td>';
}
?>
Upvotes: 1
Reputation: 2505
You have to change the order of your loops:
Your foreach
loop loops through the quantities and contains the for
loop, that loops through the days. This leads to the behavior, that the for
loop runs completely through for each quantity, therefore echoing 31 days.
This means that for 2 quantities 62 days are printed.
You need to flip the loops and add a conditional output to them:
for ($i = 1; $i <= 31; $i++) {
$quantity = '-';
foreach ($qty_day as $qd) {
list($qty,$day) = explode('/', $qd);
if ($day == $i) {
$quantity = $qty;
break;
}
}
echo '<td>' . $quantity . '</td>';
}
Upvotes: 1
Reputation: 5203
Try this way, creating an associative array first with the day and value:
<?php
$qty_n_day = '1/2,3/6';
$qty_day = explode(',', $qty_n_day);
$days = [];
foreach ($qty_day as $day) {
if (($res = explode('/', $day))) {
$days[$res[1]] = $res[0];
}
}
/*
the array should stay like this
$days = [
2 => 1,
6 => 3
];
*/
for($i = 1; $i<=31;$i++){
if (isset($days[$i])) { // if the key exists set the value
echo '<td>' . $days[$i] . '</td>';
} else {
echo '<td>-</td>';
}
}
?>
Upvotes: 3