在 php 中将对象推送到数组时,所有对象都是一样的


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

我想将许多对象推送到一个数组中

并且每个对象具有不同的值

但是当我将它们推入阵列时

它们的所有值都相同

如何解决这个问题?

$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);

这是因为您每次都将相同的对象推送到数组中。

您应该改为在每次迭代中推送一个新对象。例如,如果$ostdClass对象,请在循环中使用$o = new stdClass

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

您也可以使用 mysql_fetch_object ,这可能更合适:

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

上述对象的属性将根据您的 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);
}

尝试先声明$o(在 while 循环内):

$o = new stdClass;

这是因为对象作为引用被添加到数组中。 数组中的每个元素都是对一个对象的引用,即同一个对象。

你没有声明$o,所以当你第一次做$o->pw时,PHP 会为你创建一个对象。 当它这样做时,它会在循环范围之外创建它,因此循环的每次迭代都引用相同的$o

您需要声明$o每个循环迭代。

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

你真的不需要在 php 中使用 push 太多,你可以使用空括号来填充它。不确定它是否有区别,但我发现括号更容易。此外,O 似乎没有在此代码中定义,也没有在循环中重置。这可能是问题的来源,尽管我总体上不太清楚你的问题。祝你好运

$sql="select password, mail from account";
$result=mysql_query($sql);
$arr=array();
while($row=mysql_fetch_assoc($result))
{
    //define/reset o here
    $o->pw=$row['password'];
    $o->mail=$row['mail'];
    $arr[] = $o;
}
echo json_encode($arr);

我认为您需要为循环的每次迭代实例一个新对象。 现在,循环的每次迭代只有一个$o被写入,这就是为什么它们看起来都具有相同的值:它们是相同的。

试试这个:

while($row=mysql_fetch_assoc($result))
{
    $o = new stdClass();
    $o->pw=$row['password'];
    $o->mail=$row['mail'];
    array_push($arr, $o);
}
$sql="select password, mail from account"; 
$result=mysql_query($sql);
$data = [];
while($row=mysql_fetch_assoc($result)){
array_push($data, ['password' => $row['password'],
           'mail' => $row['mail'],]);
}
header('Content-Type: application/json');
$encode_data = json_encode($data);
echo $encode_data;