停止在 while 内循环 foreach

我尝试使用数组从数据库中获取数据。但是当我在 while 中组合 foreach 时,它会在数据库中循环尽可能多的数据。如何停止循环?我已经实现了中断功能,但不起作用。我的代码中缺少什么。


这是我的代码:


<?php

  $no=1;                                

  if(mysqli_num_rows($query) > 0)

    {

      $useArray = array("A","B","B","C");

      while($row = mysqli_fetch_array($query))

      {

        foreach ($useArray as $array)

        {

          echo"<tr>";

          echo "<td>".$no."</td>";

          echo "<td>".$row['id']."</td>";

          echo "<td>".$row['name']."</td>";

          echo "<td>".$row['grade']."</td>";

          if($row['v1']>=2.000)

            echo "<td class='bg-success'>".$row['v1']."</td>";

          elseif($row['v1']>=1.500)

            echo "<td class='bg-warning'>".$row['v1']."</td>";

          elseif($row['v1']>=0.100)

            echo "<td class='bg-danger'>".$row['v1']."</td>";

          else

          {

            echo "<td class='bg-dark'>".$row['v1']."<h5>D</h5></td>";

          }

          echo "<td>".$array."</td>";

          if ($array == "C") {

            break;

           }

          echo "</tr>";

        }

      $no++;

    }

  }

 else

  {

?>

</tbody>

</table>

<?php

echo "No Point";

}

?>

结果如下

https://img1.mukewang.com/6519247a00014b7001640524.jpg

我先搜索,但没有工作。也许我错误地实现了代码。这是我的参考: 在 PHP 中结合 foreach 和 while ,突破 if 和 foreach

我的预期结果是:

https://img2.mukewang.com/651924860001138b02000137.jpg

总数据由数组中的字符串数量决定,因此如果数组为 ("A","B","B","C"),那么数据库中也只有 4 行。任何帮助表示赞赏。



慕仙森
浏览 57回答 2
2回答

蛊毒传说

break只留下附近的方块。在你的代码中:while($continue && $row = mysqli_fetch_array($query)){&nbsp; &nbsp; foreach ($useArray as $array)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo "<tr>";&nbsp; &nbsp; &nbsp; &nbsp; echo "<td>".$no."</td>";&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; if ($array == "C") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; echo "</tr>";&nbsp; &nbsp; }&nbsp; $no++;}中断离开 foreach,但 while 继续。您可以添加一个变量来保留 while,例如:$continue = true;while($continue && $row = mysqli_fetch_array($query)){&nbsp; &nbsp; foreach ($useArray as $array)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo "<tr>";&nbsp; &nbsp; &nbsp; &nbsp; echo "<td>".$no."</td>";&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; if ($array == "C") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $continue = fase;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; echo "</tr>";&nbsp; &nbsp; }&nbsp; $no++;}

饮歌长啸

这里发生的事情是你break破坏了foreach, 而不是循环遍历数据库查询的 while 。您可以尝试在使用时突破break 2。这里2表示您试图跳出多少个“可破坏”循环。尽管如此,我相信您可以通过修改数据库查询来改进代码,以避免不必要的循环。
打开App,查看更多内容
随时随地看视频慕课网APP