CL *_* So 4 php arrays json object
我想将许多对象推入数组
每个对象都有不同的价值
但是当我把它们推入阵列时
它们的所有值都是相同的
如何解决这个问题呢?
$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);
Run Code Online (Sandbox Code Playgroud)
那是因为你每次都将同一个对象推入数组.
您应该在每次迭代中推送一个新对象.例如,如果$o
是stdClass
对象,则$o = new stdClass
在循环内部使用:
while($row=mysql_fetch_assoc($result))
{
$o = new stdClass;
$o->pw=$row['password'];
$o->mail=$row['mail'];
array_push($arr, $o);
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用mysql_fetch_object
,这可能更合适:
while($o=mysql_fetch_object($result))
{
array_push($arr, $o);
}
Run Code Online (Sandbox Code Playgroud)
将根据您的SQL查询列命名上述对象的属性,因此要实现相同的效果,您还需要将查询更改为select password AS pw, mail from account
.
最后,另一种选择是每次克隆对象 - 尽管其他替代方案几乎总是更可取:
while($row=mysql_fetch_assoc($result))
{
$o = clone $o;
$o->pw=$row['password'];
$o->mail=$row['mail'];
array_push($arr, $o);
}
Run Code Online (Sandbox Code Playgroud)