gpt4 book ai didi

php - while 和 foreach 获取 PDO::FETCH_OBJECT 时的不同行为

转载 作者:行者123 更新时间:2023-11-29 11:14:05 25 4
gpt4 key购买 nike

当使用类似的东西时:

$db = new PDO(connection_details)
$query = "SELECT * FROM vservers LIMIT 5";
$result = $db->query($query);

然后尝试使用 while f.e. 获取记录

while ($row = $result->fetchAll(PDO::FETCH_OBJ)) {
var_dump($row);
}

它返回一个带有 StdObjects 的数组,如下所示:

array (size=5)
0 =>
object(stdClass)[3]
public 'vserverid' => string '898' (length=3)
public 'templatename' => string 'Debian' (length=14)
public 'template' => string 'debian-7.0-x86' (length=14)
1 =>
object(stdClass)[4]
public 'vserverid' => string '792' (length=3)
public 'templatename' => string 'Ubuntu' (length=33)
public 'template' => string 'ubuntu-15.04' (length=27)

使用 foreach 它返回 StdObjects

    foreach ($result->fetchAll(PDO::FETCH_OBJ) as $key) {
var_dump($key);
}

object(stdClass)[3]
public 'vserverid' => string '898' (length=3)
public 'templatename' => string 'Debian' (length=6)
public 'template' => string 'debian' (length=6)


object(stdClass)[4]
public 'vserverid' => string '792' (length=3)
public 'templatename' => string 'Ubuntu' (length=6)
public 'template' => string 'ubuntu' (length=6)

有人可以解释一下这种行为吗?通常,我想像 foreach 一样返回对象,但这是一个好的做法吗?

最佳答案

fetchAll() 以数组形式返回所有结果,其中每个元素都是代表表中一行的对象。

while 代码中,第一次迭代将 $row 设置为整个结果集,并将其转储为单个数组。只有一次迭代,因为下一次调用 fetchAll() 返回一个空数组,因为没有任何内容可供提取。

foreach 代码中,fetchAll() 将数组返回给 foreach,然后一次迭代一个元素,设置每个对象的 $key 。然后你把那个物体扔进你的 body 里。

通常,当您使用 while 时,您会使用 fetch(),而不是 fetchAll()。此代码相当于 foreach:

while ($key = $result->fetch(PDO::FETCH_OBJ)) {
var_dump($key);
}

关于php - while 和 foreach 获取 PDO::FETCH_OBJECT 时的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40052503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com