【问题标题】:Populate array of class type in PHP在 PHP 中填充类类型的数组
【发布时间】:2023-04-03 17:05:02
【问题描述】:

如何使用从类中的数据库中检索到的数据填充数组,以使数组中的数据为对象类型 Fuelprices?

class Fuelprices {

     private $year;
     private $coal;

     private $data = array();

     public function __construct($year, $coal) {
         $this->year = $year;
         $this->coal = $coal;
     }

     public function arrayContainingObjects() {
         $arrayFromDatabase = array(
             array('year' => 2010, 'coal' => 22.54),
             array('year' => 2011, 'coal' => 42.87),
             ...
             );
         // fill $data-array with object of Fuelprices object type 
         return $data;
     }

}

$array = $instanceOfFuelpricesClass->arrayContainingObjects();

...所以$array的内容是这样的

array(
     object1,
     object2,
     ...
);

【问题讨论】:

  • 只需将new Fuelprices($year, $coal)s 推入数组即可。
  • 为什么这是 Fuelprices 实例上的函数?

标签: php arrays class populate


【解决方案1】:

只需将new Fuelprices($year, $coal) 对象添加到数组中即可。

foreach($arrayFromDatabase as $theData){
    $data[] = new Fuelprices($theData['year'], $theData['coal']);
}

【讨论】:

  • 感谢火箭。很简单。虽然我不得不将班级成员从私人更改为公共,但它可以作为一种魅力。
【解决方案2】:

使用 PDO,如果您的类具有与列名匹配的公共属性,则可以使用$PDO::FETCH_CLASS,请参阅online docs。对于大型结果集,这将比将它们全部加载到内存中的数组中更有效。

<?php
$stmt = $pdo->prepare($sql);

$stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, "FuelPrices");

# pass parameters, if required by the query
$stmt->execute($parameters);

foreach ($stmt as $row) {
    // do something with (each of) your object
}

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2019-01-25
    • 1970-01-01
    • 2022-01-19
    • 2023-03-29
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多