我想使用填充在php数组中的数据创建动态html选项字段。但是我的问题是,当我打开包含代码的页面时,服务器“崩溃”,这意味着它加载非常缓慢,并且页面冻结时也没有显示整个页面。
我想知道为什么这么简单的代码会发生这种情况。

<?php
          if(isset($variants)){
            echo '<label for="exampleRecipientInput">Size</label>';
            echo '<select id="exampleRecipientInput">';
            for ($i = 0; $i < $variants; $i++) {
              echo '<option value="Option ',$i, ' ">',$variants[$i],'</option>';
            }
            echo '</select>';
          }
?>


包含数组的数据按以下方式创建

if (array_key_exists('Variants', $array[$productNumber])) {
      $variants = explode(",",$array[$productNumber]['Variants']);
}

最佳答案

由于$ variants是一个数组,因此必须使用count(),或者更好的方法是使用foreach。

在当前情况下,循环永远不会停止,这就是服务器崩溃的原因。

<?php
          if(isset($variants)){
            echo '<label for="exampleRecipientInput">Size</label>';
            echo '<select id="exampleRecipientInput">';
            foreach ($variants as $key => $val) {
              echo '<option value="Option ',$key, ' ">',$val,'</option>';
            }
            echo '</select>';
          }
?>

10-05 20:33
查看更多