php 如何强制 PDOStatement->fetchAll 返回对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8370647/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:32:58  来源:igfitidea点击:

How to force PDOStatement->fetchAll to return array of objects?

phpobjectpdo

提问by Elektryk

I am writing my own simply ORM using PDO. My question is if you can force PDOStatement::fetchAll()method to return array of objects of stdClass? For example:

我正在使用 PDO 编写自己的简单 ORM。我的问题是你是否可以强制PDOStatement::fetchAll()方法返回 stdClass 的对象数组?例如:

$result = $q->fetch_all(/* some magic here */);
print_r($result);

Should print something like:

应该打印如下内容:

Array
(
    [0] => stdClass Object
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => stdClass Object
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )

)

Is this posible? NAME and COLOUR are of course names of columns. I read documentation but I didn't find anything interesting.

这可能吗?NAME 和 COLOR 当然是列的名称。我阅读了文档,但没有发现任何有趣的东西。

回答by

Use $result = $q->fetchAll(PDO::FETCH_OBJ);

$result = $q->fetchAll(PDO::FETCH_OBJ);

回答by vimist

This will do it:

这将做到:

 <?php
 $sth = $dbh->prepare("SELECT name, colour FROM fruit");
 $sth->execute();

 $result = $q->fetchAll(PDO::FETCH_OBJ);
 //$result contains an array of stdObjects
 ?>

However even cooler way is to get PDO to instantiate your own class and populate the properties for you:

然而,更酷的方法是让 PDO 实例化你自己的类并为你填充属性:

Example #4 Instantiating a class for each result

The following example demonstrates the behaviour of the PDO::FETCH_CLASS fetch style.

Example #4 为每个结果实例化一个类

以下示例演示 PDO::FETCH_CLASS 获取样式的行为。

 <?php
 class fruit {
     public $name;
     public $colour;
 }

 $sth = $dbh->prepare("SELECT name, colour FROM fruit");
 $sth->execute();

 $result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
 //$result contains an array of fruit objects
 ?>

Source: http://www.php.net/manual/en/pdostatement.fetchall.php

来源:http: //www.php.net/manual/en/pdostatement.fetchall.php

回答by kaizenCoder

You should also be able to do the following:

您还应该能够执行以下操作:

$stmt->setFetchMode(PDO::FETCH_OBJ); //set the mode for all fetch request

With any subsequent fetchrequest you can omit explicitly specifying the mode.

对于任何后续fetch请求,您可以省略显式指定模式。

$stmt->setFetchAll(); //returns an array of objects