数组的循环问题

问题描述 投票:1回答:3
    <?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>

输出结果enter image description here我的预期结果enter image description here

  1. 31列表示为天。
  2. 我将数量和天数存储在一起,然后将其提取到列表中。
  3. 之后,我想将它与日期列进行比较并显示该列的数量值。

我怎样才能做到这一点?我的逻辑错了吗?

php html arrays loops
3个回答
3
投票

尝试这种方式,首先使用日期和值创建关联数组:

<?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>';
        }
    }

?>

1
投票

你必须改变你的循环的顺序:你的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>';
}

1
投票

这个问题源于你正在进行两次迭代,第一次处理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>';
    }

?>
© www.soinside.com 2019 - 2024. All rights reserved.