PHP WHILE语句在数组长度上迭代



我通过观看一些carts教程学习了一些oop,并在我认为相同的事情上发现了两种不同的行为,我无法理解为什么:1-while starnt应该在条件为TRUE时迭代,但我看到代码只根据作为参数提供的数组的长度进行迭代(这对我来说没有意义,但它确实有意义(:这是一个例子:

while ($row = mysqli_fetch_assoc($result)){

echo '<pre>'; print_r($row); echo '</pre>';
// component($row['product_name'], $row['product_price'], $row['product_image'], $row['id']);
}

在上面的情况下,它只迭代4次,因为这是数组的长度。

但后来我试着复制这个来检查

<?php
$test = ["nro1" =>1 , "nro2" => 2];
while ($test){
print_r($test); 
}

和它的永远迭代,(这是有意义的,因为数组总是TRUE,与它的长度无关(

有人能帮我解释一下吗?非常感谢。

第一个片段是每次通过循环调用mysqli_fetch_assoc()。每次调用它时,它都会以数组的形式返回查询的下一行结果。

当它到达结果的末尾时,它返回FALSE。这会导致条件失败,并且循环退出。

您的第二个代码段将永远循环,因为$test永远不会更改。

第一种情况不是数组,而是mysqli_result对象。在调用函数时,它会移动mysqli_result的内部指针,直到返回false。第二种情况是,您只循环相同的变量,该变量将始终计算为true。你可以"模仿";类似的行为

<?php
$test = ["nro1" =>1 , "nro2" => 2];
while ($item = current($test)) {
print_r($item); 
next($test);
}

或者更好:

<?php
$test = [1,2,3];
while ($item = current($test)) {
echo $item;
next($test);
}
bro , in the first example, if u look better :
while ($row = mysqli_fetch_assoc($result)){}
the mysqli_fetch_assoc is a function that can count the MYSQL results COUNT.
i mean that function developed for the MySQL select query results.
but in the second Example:
while ($test)
while continue until the condition is TRUE,
when u use condition like this, that's only means , If $test DEFINED, then Exit Loop, else Continue.
you better use FOR EACH instead While.
For Each($test as $item){
//do something
}

最新更新