Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When push objects to array in php, all objects are same

I want to push many objects into a array

and each object have different value

but when I pushed them into array

all values of them are same

how to solve this problem?

$sql="select password, mail from account";
$result=mysql_query($sql);
$arr=array();
while($row=mysql_fetch_assoc($result))
{
    $o->pw=$row['password'];
    $o->mail=$row['mail'];
    array_push($arr, $o);
}
echo json_encode($arr);
like image 972
CL So Avatar asked Dec 02 '22 22:12

CL So


1 Answers

That's because you are pushing the same object into the array each time.

You should push a new object in each iteration instead. For example, if $o is a stdClass object, use $o = new stdClass inside the loop:

while($row=mysql_fetch_assoc($result))
{
    $o = new stdClass;
    $o->pw=$row['password'];
    $o->mail=$row['mail'];
    array_push($arr, $o);
}

You can also use mysql_fetch_object, which is perhaps more appropriate:

while($o=mysql_fetch_object($result))
{
    array_push($arr, $o);
}

The properties on the above object will be named based on your SQL query columns, so to achieve the same effect you would also need to change the query to select password AS pw, mail from account.

Finally, another option is to clone the object each time -- although the other alternatives are almost always preferable:

while($row=mysql_fetch_assoc($result))
{
    $o = clone $o;
    $o->pw=$row['password'];
    $o->mail=$row['mail'];
    array_push($arr, $o);
}
like image 170
Jon Avatar answered Dec 23 '22 13:12

Jon