在foreach循环中导致额外原始的原因是什么?

时间:2015-03-19 09:24:06

标签: php mysqli

我有一个for循环,用于打印订单的特定销售商品的序列号,这是基于this question

完成的
    if (($c["current_state"] == '16') || ($c["current_state"] == '4')) {
        $snlst = $mysqli->query("SELECT sn FROM ps_serials WHERE id_product={$aritmlst["product_id"]} AND id_order=$oid ORDER BY sn ASC");

        while ($id = mysqli_fetch_array($snlst)) {
            $ids[] = $id;
            foreach ($ids as $key => $id) {
                echo "<tr><td class=\"label\" style=\"padding-left:15px\">Serial Number ".($key +1)."</td><td>".$id['sn']."</td></tr>";
            }
        }
    } 

但问题是我为我的列表添加了一个额外的表格。那是为什么?

enter image description here

3 个答案:

答案 0 :(得分:1)

我不认为需要两个循环。恕我直言这应该是足够的代码:

if (($c["current_state"] == '16') || ($c["current_state"] == '4')) {
    $snlst = $mysqli->query("SELECT sn FROM ps_serials WHERE id_product={$aritmlst["product_id"]} AND id_order=$oid ORDER BY sn ASC");
    $i = 0;
    while ($row = mysqli_fetch_array($snlst)) {
        $i++;
        echo '<tr><td class="label" style="padding-left:15px">Serial Number ' . $i . '</td><td>' . $row['sn'] . '</td></tr>' . PHP_EOL;
    }
}

答案 1 :(得分:0)

重写这一行:

while ($id = mysqli_fetch_array($snlst)) {
            $ids[] = $id;
            foreach ($ids as $key => $id) {
                echo "<tr><td class=\"label\" style=\"padding-left:15px\">Serial Number ".($key +1)."</td><td>".$id['sn']."</td></tr>";
            }
        }

到此:

while ($id = mysqli_fetch_array($snlst)) {
    $ids[] = $id;       
}
foreach ($ids as $key => $id) {
 echo "<tr><td class=\"label\" style=\"padding-left:15px\">Serial Number ".($key +1)."</td><td>".$id['sn']."</td></tr>";
            }

答案 2 :(得分:0)

然后尝试一个简单的for循环,而不是foreach循环:

for($i= 0; $i < count($ids); $i++)
{
  echo "<tr><td class=\"label\" style=\"padding-left:15px\">Serial Number ".($i+1)."</td><td>".$ids[$i]['sn']."</td></tr>";
}