在 PHP 中 while 循环的参数中调用函数


Calling a function within the parameter of while loop in PHP

我已经在这个概念上停留了大约 5 个小时,这真的让我感到沮丧。

$result = $mysqli->query("SELECT col FROM table");
while($row = $result->fetch_assoc()){
    echo $row['data'];
}

我知道该函数一次只获取一行,但我不明白循环重置时如何调用它。$row = $result->fetch_assoc怎么称呼?此外,如果 $row 为 null,则此条件的计算结果如何为 true?

好的,这是给你的简单测试,

让我们有一个具有价值的array

,其null如下所示,
$row = array('value' => null);

现在让我们使用if条件进行检查

if($row)
{
    echo "null is making variable value to true so condition will work.";
}

粘贴coderun它,我相信您会在if条件中看到消息。

您的状况

您正在使用$result->fetch_assoc(),因此如您所知,它将返回可能具有null值的array如上例所示。

但如您所见,它将返回$resulttrue,因为$result实际上分配了值并且它是true .

所以条件会得到满足。

简而言之,while 循环条件正在寻找true

while(true){
//do this
}

因此,在此表达式$row = $result->fetch_assoc()解析为true之前,while 循环将继续。

问题是什么时候会不是真的?当检索到所有行时。

如果 $row 为 null,则此条件的计算结果如何为 true?

其实不然。这就是重点。

给定您的代码:

while($row = $result->fetch_assoc()){
    echo $row['data'];
}

循环条件可以重写为以下等效条件:

while (($row = $result->fetch_assoc()) != false) {
    echo $row['data'];
}

换句话说,虽然$row不是假的,但它将继续循环; null也被认为是假的。

以下对代码的解释可能会对您有所帮助

// run the query. this returns a mysqli_result object on success.
// on failure query function returns false and you have to handle this condition.
$result = $mysqli->query("SELECT col FROM table");
// fetch_assoc() here you fetch one row at a time from the mysqli_result
// object into $row. this also moves the pointer to the next row
// so the next call returns the next row.
// This returns false when there is no more rows and exit your while loop
while($row = $result->fetch_assoc()){
    echo $row['data'];
}

您可能想要参考
的链接
http://www.php.net/manual/en/class.mysqli-result.phphttp://php.net/manual/en/mysqli-result.fetch-assoc.php