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;
}
0

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

this is much better.+1
@Syscall, Thank you. Which is better in general?
@TeMe Between what and what? PDO and MySQLi or arrays and objects? Is mostly as you prefer, IMHO. Maybe it could depends of what you have to do with your data after that.
@Syscall Between arrays and objects
@TeMe As I said in my updated comment, it could depends of what you have to do with your data after that.
0

You can try like this

$object = new stdClass();

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

Or refer to this answer

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.