简体   繁体   English

While和foreach与获取PDO :: FETCH_OBJECT的不同行为

[英]While and foreach different behaviour with fetching PDO::FETCH_OBJECT

While using something like: 在使用类似的东西时:

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

And then try to get records with while fe 然后尝试使用fe

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

it returns an array with StdObjects like this: 它返回一个带有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)

And with foreach it returns StdObjects 并与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)

Can someone please explain this behaviour? 有人可以解释一下这种行为吗? Normally, I would like to return Objects like with foreach , but is it a good practice ? 通常,我想使用foreach来返回Object,但这是一个好习惯吗?

fetchAll() returns all the results as an array, where each element is an object that represents a row from the table. fetchAll()以数组的形式返回所有结果,其中每个元素都是一个代表表中一行的对象。

In your while code, the first iteration sets $row to the entire result set, and dumps it as a single array. while代码中,第一次迭代将$row设置$row整个结果集,并将其转储为单个数组。 There's only one iteration because the next call to fetchAll() returns an empty array, because there's nothing left to fetch. 仅有一次迭代,因为对fetchAll()的下一次调用返回了一个空数组,因为没有什么可提取的。

In your foreach code, fetchAll() returns the array to foreach , which then iterates over it one element at a time, setting $key to each object. 在您的foreach代码中, fetchAll()将数组返回到foreach ,然后数组一次遍历一个元素,并为每个对象设置$key Then you dump that one object in your body. 然后,您将那个物体扔到体内。

Normally when you're using while you use fetch() , not fetchAll() . 通常情况下,当你使用while ,你使用fetch() ,而不是fetchAll() This code will be equivalent to the foreach : 该代码将等同于foreach

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM