php 理解 fetch_assoc()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39267773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Understanding fetch_assoc()
提问by Gordog
I am trying to understand how/why fetch_assoc works the way it does. I have the following piece of code:
我试图了解 fetch_assoc 如何/为什么以这种方式工作。我有以下一段代码:
$results = $connectToDb->fetch("SELECT * FROM customer");
$resultsArray = $results->fetch_assoc();
print_r($resultsArray); //print_r 1
while($row = $results->fetch_assoc()){
print_r($row); //print_r 2
}
The query returns 3 rows from a table. Why does the 1st print_r return only the 1st row of the queried data but the 2nd print_r returns all 3? How does putting fetch_assoc into a while loop tell it to do the action more than once? I read that fetch_assoc returns either an associative array or NULL but I'm struggling to understand how the while loop "tells" fetch_assoc to fetch the next row, if that makes sense?
该查询从表中返回 3 行。为什么第一个 print_r 只返回查询数据的第一行,而第二个 print_r 返回全部 3?将 fetch_assoc 放入 while 循环如何告诉它多次执行操作?我读到 fetch_assoc 返回一个关联数组或 NULL 但我很难理解 while 循环如何“告诉” fetch_assoc 获取下一行,如果这有意义吗?
Thank you.
谢谢你。
回答by Andrej Ludinovskov
Lets try to understand your code and how it works:
让我们尝试了解您的代码及其工作原理:
$results = $connectToDb->fetch("SELECT * FROM customer");
A variable $results
has a collection of rows which are returned by a query. The size of the collection can be from 0 to n.
变量$results
具有由查询返回的行的集合。集合的大小可以从 0 到 n。
$resultsArray = $results->fetch_assoc();
This line fetch the first element from the collection. If the collection is empty it will return NULL
.
这一行从集合中获取第一个元素。如果集合为空,它将返回NULL
。
while($row = $results->fetch_assoc()){
}
It can be decoupled in the following steps:
它可以通过以下步骤解耦:
- Calculate
$row = $results->fetch_assoc()
and return array with elementsor NULL. - Substitute
$row = $results->fetch_assoc()
inwhile
with gotten value and get the following statements:while(array(with elements))
orwhile(NULL)
. - If it's
while(array(with elements))
it resolves the while condition inTrue
and allow to perform an iteration. - If it's
while(NULL)
it resolves the while condition inFalse
and exits the loop.
- 计算
$row = $results->fetch_assoc()
并返回带有元素或NULL 的数组。 - 用得到的值替换
$row = $results->fetch_assoc()
inwhile
并得到以下语句:while(array(with elements))
或while(NULL)
。 - 如果是,
while(array(with elements))
它会解决 while 条件True
并允许执行迭代。 - 如果是,
while(NULL)
它将解决 while 条件False
并退出循环。