【问题标题】:Why does this loop return 1 when using && instead of 'and'?为什么这个循环在使用 && 而不是 'and' 时返回 1?
【发布时间】:2010-02-07 03:30:57
【问题描述】:

谜语...在while($row = mysql_fetch_assoc($result) and $runningOK) 循环中,如果使用PHP && 运算符代替and,那么mysql_fetch_assoc 将严重失败,并且在运行时仅返回数字1

我已经尝试了mysql_fetch_array() 并且我仍然遇到1 的问题。只有当且仅当我将&& 替换为and (如当前的while 语句)时才会返回正确的行。

我在之前、内部和之后放置了调试语句以确保这一点。我想知道这是 PHP 的怪癖还是我无法解释的原因。

// Query
$selectQuery = "SELECT * FROM jobs_cache LIMIT 20";
// Run the Selection Query.
$result = mysql_query($selectQuery)
    or die('Query Failed: '.mysql_error());

// Loop through results.
$runningOK = TRUE;
$resubmitList = array();

while($row = mysql_fetch_assoc($result) and $runningOK)
{
    // Resubmit The Job
    try
    {
        $client->addTaskBackground($row['function_name'],$row['job_data']);
        $resubmitList[] = (string)$row['job_cache_id'];
    }
    catch(Exception $e)
    {
        echo "Error adding task for job id: " . $row['job_cache_id'];
        $runningOK = FALSE;
    }
}

【问题讨论】:

    标签: logic php gearman


    【解决方案1】:

    这是由于运算符优先级。有关详细信息,请参阅the manual...这是相关部分。

    // "&&" 的优先级高于 “和”

    // 将表达式的结果(true && false)赋值给$g
    // 类似于:($g = (true && false))

    $g = true && false;

    // 将常量 true 赋值给 $h,然后忽略 false
    // 类似:(($h = true) and false)

    $h = 真假;

    var_dump($g, $h);

    布尔(假)
    布尔(真)

    因此,使用 && 时,表达式的结果被赋值为 true,其计算结果为 1。使用 and,它计算结果为 mysql 函数的结果——我想你想要的更多。

    顺便说一句,您也可以使用break 来消除对 $runningOK 变量的需要。为此,请从while 条件中删除 and $runningOK,并将$runningOK = FALSE; 更改为break;,如果触发了catch 块,它将结束循环。

    【讨论】:

    • 这是一个更大的 Gearman Worker 内核的片段,运行 ok 用于几个部分以确保我们有有效的 SQL 调用和 worker 健康。对优先级的解释多么美妙而清晰!
    • 也很高兴获得 1000 个代表 :)
    • 谢谢!我正在用冰淇淋庆祝。
    【解决方案2】:

    试试这个:

    while(($row = mysql_fetch_assoc($result)) and $runningOK)
    

    可能会出现混淆,因为它会将 mysql_fetch_assoc($result) and $runningOK 评估为 TRUE,然后将其分配给 $row,在这种情况下与 1 相同

    如果您添加括号,您很可能可以使用&&and,因为您将正确分隔两个评估。

    我敢肯定,这是替代语法的副作用。

    【讨论】:

    • 我的钱花在了这个解释上。
    【解决方案3】:

    赋值运算符=和两个逻辑运算符&&ANDdifferent precedence&&=之前执行,而AND又在AND之前执行

    所以基本上是这样的声明:

    $row = mysql_fetch_assoc($result) AND $runningOK
    

    等于:

    ($row = mysql_fetch_assoc($result)) AND $runningOK
    

    while 语句:

    $row = mysql_fetch_assoc($result) && $runningOK
    

    等于:

    $row = (mysql_fetch_assoc($result) && $runningOK)
    

    在最后一种情况下,您只是分配值 1(如果 mysql_fetch_assoc 返回值)或 0。

    【讨论】:

      【解决方案4】:

      这是因为运算符解决了优先级。

      查看此表以了解:

      http://php.net/manual/en/language.operators.precedence.php

      当你不知道它是如何解决的时候,尽可能多地使用 ()。

      【讨论】:

        猜你喜欢
        • 2014-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        • 2023-03-28
        • 2023-01-02
        相关资源
        最近更新 更多