Question

How would one go about in filling an array with data that has been retrieved from the database inside a class so that the data in the array is of object type 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();

...so the content of $array is this

array(
     object1,
     object2,
     ...
);
Was it helpful?

Solution

Just simply add new Fuelprices($year, $coal) objects into the array.

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

OTHER TIPS

With PDO, if your class has public properties matching the column nams, you can use $PDO::FETCH_CLASS, see the online docs. For large resultsets, this will be more efficient that loading them all into an array in memory.

<?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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top