在达到极限之前,foreach循环中断

时间:2018-03-29 06:49:21

标签: php mysql foreach

我一直在尝试使用以下代码为每个学生列出9个表 -

最多可成功打印8条记录。但是对于 $ s 的下一个值,下一个学生会被列出。

我在哪里弄错了?

$query="SELECT * FROM `member_db` WHERE Class='$class' ORDER BY `Member_name` ASC";
$Result = mysqli_query($conn, $query);
$s=1;
while($row=mysqli_fetch_array($Result)) {
    foreach($row as $field) {
        if($s==10){
            $s=1; break;
        } else if($s==1){
            $sub="English (WS VOL-1)";
        } else if($s==2){
            $sub="English (WS VOL-2)";
        } else if($s==3){
            $sub="English (WS VOL-3)";
        } else if($s==4){
            $sub="Maths (WS VOL-1)";
        } else if($s==5){
            $sub="Maths (WS VOL-2)";
        } else if($s==6){
            $sub="Maths (WS VOL-3)";
        } else if($s==7){
            $sub="Science (WS VOL-1)";
        } else if($s==8){
            $sub="Science (WS VOL-2)";
        } else if($s==9){
            $sub="Science (WS VOL-3)";
        }

        echo $table;
        $s++;
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个:$ i ++应该在结束内循环之后。

<?php

$query = "SELECT * FROM `member_db` WHERE Class='$class' ORDER BY `Member_name` ASC";
$Result = mysqli_query($conn, $query);
$s = 1;
while ($row = mysqli_fetch_array($Result)) {
    foreach ($row as $field) {
        if ($s == 10) {
            $s = 1;
            break;
        }

        if ($s == 1) {
            $sub = "English (WS VOL-1)";
        } elseif ($s == 2) {
            $sub = "English (WS VOL-2)";
        } elseif ($s == 3) {
            $sub = "English (WS VOL-3)";
        } elseif ($s == 4) {
            $sub = "Maths (WS VOL-1)";
        } elseif ($s == 5) {
            $sub = "Maths (WS VOL-2)";
        } elseif ($s == 6) {
            $sub = "Maths (WS VOL-3)";
        } elseif ($s == 7) {
            $sub = "Science (WS VOL-1)";
        } elseif ($s == 8) {
            $sub = "Science (WS VOL-2)";
        } elseif ($s == 9) {
            $sub = "Science (WS VOL-3)";
        }
        echo $table;

    }
    $s++; //this is only change
}