<?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>
我怎样才能做到这一点?我的逻辑错了吗?
尝试这种方式,首先使用日期和值创建关联数组:
<?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>';
}
}
?>
你必须改变你的循环的顺序:你的foreach
循环遍历数量并包含for
循环,循环遍历日子。这导致行为,for
循环完全贯穿每个数量,因此回响31天。这意味着对于2个数量,打印62天。
您需要翻转循环并向它们添加条件输出:
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>';
}
这个问题源于你正在进行两次迭代,第一次处理2
循环,第二次处理31
循环......生成总共62
元素。
我建议你一个更紧凑的解决方案,首先构建最终的数组,然后简单地打印它:
<?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>';
}
?>