代码之家  ›  专栏  ›  技术社区  ›  Wyatt Jackson

如何从php 7中的嵌套include文件中断while循环?

  •  0
  • Wyatt Jackson  · 技术社区  · 8 年前

    我有一个while循环,其中包括几个复杂的函数,因为它在mysql记录中循环。其中一个更简单的任务是检查变量$city是否有一个±符号,如果$city包含一个±符号,那么需要跳过mysql记录,但是对于剩余的mysql记录,循环需要继续。

    在过去,我用了“break”;来解决这个问题,但我收到了这个错误:

    php致命错误:“break”不在“loop”或“switch”上下文中

    我读过,我应该使用“返回错误”;相反,但这似乎也不起作用。

    任何帮助都非常感谢。

    测试程序

    <?PHP
    
    $query = "SELECT * FROM Cities limit 5";
    $result = mysqli_query($con, $query);
    
    while($row = mysqli_fetch_assoc($result))
        {
        $city = $row['City'];
        $city = "ñ";  // I hardcoded for testing
        require "test_function.php";
        echo "I should not see this if there is a ñ within $city \n\n";
    }
    
    ?>
    

    test_函数.php

    <?PHP
    
    if( strpos( $city, "ñ" ) !== false) {
        echo "City $city contains a ñ.  Skipping...\n\n";
            break;
    }
    
    ?>
    
    3 回复  |  直到 8 年前
        1
  •  1
  •   Barmar    8 年前

    如果你只想跳过一个城市,你应该使用 continue 不是 break . 持续 转到下一个循环迭代, 打破 完全结束循环。

    但是,这些语句必须在循环体中,不能在它调用的函数或包含文件中。

    您可以做的是让include文件设置一个变量,然后检查它后面的变量。

    test_函数.php

    <?PHP
    
    if( strpos( $city, "ñ" ) !== false) {
        echo "City $city contains a ñ.  Skipping...\n\n";
        $skip_city = true;
    } else {
        $skip_city = false;
    }
    
    ?>
    

    测试程序

        2
  •  0
  •   Sujan Gainju    8 年前

    为什么在循环中包含其他PHP文件?在循环中应用条件,如果条件匹配,它将脱离循环。

    <?PHP
    
    $query = "SELECT * FROM Cities limit 5";
    $result = mysqli_query($con, $query);
    
    while($row = mysqli_fetch_assoc($result))
        {
        $city = $row['City'];
        if( strpos( $city, "ñ" ) !== false) {
            echo "City $city contains a ñ.  Skipping...\n\n";
            break;
        }
        echo "I should not see this if there is a ñ within $city \n\n";
    }
    ?>
    
        3
  •  0
  •   Ntwobike    8 年前

    如果找到特殊字符,这将中断迭代

    $query = "SELECT * FROM Cities limit 5";
    $result = mysqli_query($con, $query);
    $isCharFound = false;
    
    while(($row = mysqli_fetch_assoc($result)) && ($isCharFound === false))
    {
        $city = $row['City'];
        if( strpos( $city, "ñ" ) !== false) {
            echo "City $city contains a ñ.  Skipping...\n\n";
            $isCharFound = true;
            continue;
        }
        echo "I should not see this if there is a ñ within $city \n\n";
    }
    

    如果只想跳过具有特殊字符的记录

    $query = "SELECT * FROM Cities limit 5";
    $result = mysqli_query($con, $query);
    
    while($row = mysqli_fetch_assoc($result))
    {
        $city = $row['City'];
        if( strpos( $city, "ñ" ) !== false) {
            echo "City $city contains a ñ.  Skipping...\n\n";
            continue;
        }
        echo "I should not see this if there is a ñ within $city \n\n";
    }
    
    推荐文章