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);
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
$ois astdClassobject, use$o = new stdClassinside the loop:You can also use
mysql_fetch_object, which is perhaps more appropriate: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: