0

I use below code to get outputs database:

$array = array();
while($row = ...){
   $array[] = $row;
}

return $array;

Now, i can get values:

foreach($array as $in){
   echo $in[title];
}

But i want get values by -> :

foreach($array as $in){
   echo $in->title;
}
Te Me
  • 295
  • 1
  • 4
  • 9

2 Answers2

3

You could store objects during the while() loop.

Using MySQLi, with fetch_object():

while ($row = $result->fetch_object()) {
    // here, $row is an object
    $array[] = $row;
}

Using PDO, with fetch(), and the PDO::FETCH_OBJ constant:

while ($row = $sth->fetch(PDO::FETCH_OBJ)) {
    // here, $row is an object
    $array[] = $row;
}

Then you could access using ->:

foreach($array as $in){
   echo $in->title;
}
Syscall
  • 19,327
  • 10
  • 37
  • 52
0

You can try like this

$object = new stdClass();

foreach ($array as $key => $value)
{
    $object->$key = $value;
}

Or refer to this answer

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mad Coder
  • 117
  • 14