将PDO结果集转换为对象数组

问题描述 投票:2回答:5

我有一个名为Product的PHP类:

class Product {

   $id;
   $name;

}

以及另一个从数据库获取数据的类:

$stm = $this->dsn->prepare($sql);

$stm->execute();

$rst = $stm->fetchAll(PDO::FETCH_ASSOC);

如何将这个PDO结果集($ rst)转换为对象产品数组?

php object pdo crud
5个回答
4
投票

使用PDO::FETCH_CLASS自变量。

class Product {
    public $id;
    public $name;
}

$stm = $this->dsn->prepare($sql);
$stm->execute();

$result = $stm->fetchAll( PDO::FETCH_CLASS, "Product" );

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


1
投票

只需更改调用fetchAll()的方式

$rst = $stm->fetchAll(PDO::FETCH_CLASS, 'Product');

0
投票

在这种情况下,我的方法是在Product类中使用一个辅助函数,该函数将构建对象的新实例,并提供PDO的输入来返回该对象。

例如

public static function buildFromPDO($data) {
    $product = new Product();
    $product->id = $data["id"];
    $product->name = $data["name"];

    return $product;
}

然后在您的PDO调用中,将返回和array_push循环到包含通过此函数构建的所有产品的数组中。

$products = array();
foreach ($rst as $r) {
    array_push($products, Product::buildFromPDO($r));
}

[如果您似乎正在做大量此类工作,您可能还想考虑使用ORM。


0
投票

您必须编写一种方法来做到这一点。

class Product {
   $id;
   $name;
   public function loadData($data){
      $this->id = $data['id'];
      $this->name = $data['name'];
   }
}

$Product = new Product();
$Product->loadData($database_results);

或者,如果要对每个对象执行此操作,请使用构造函数。

class Product {
   $id;
   $name;
   public function __construct($id, $pdo){
      $pdo->prepare("select * from table where id = :id");
      // do your query, then...
      $this->id = $data['id'];
      $this->name = $data['name'];
   }
}

$Product = new Product($id, $pdo);

0
投票

您可以使用构造函数参数(http://php.net/manual/en/pdostatement.fetchall.php

$result = $stm->fetchAll( PDO::FETCH_CLASS, "Product", array('id','name'));

注意:属性必须是公共的

© www.soinside.com 2019 - 2024. All rights reserved.