gpt4 book ai didi

PHP array_push() 正在覆盖现有的数组元素

转载 作者:行者123 更新时间:2023-12-03 19:41:34 25 4
gpt4 key购买 nike

我正在尝试将对象插入一个数组,最终得到一个像这样的对象数组:

[
{"recipient_name":"John D", "phone_number":"123456"},
{"recipient_name":"Doe J", "phone_number":"654321"},
{"recipient_name":"Jon Do", "phone_number":"112233"},
]

所以我在一个更大的数组上循环来获取姓名和电话号码,并将它们作为一个对象推送到这样的数组中:
$myLargerArray = pg_fetch_all($messageQuery); // This is my larger array

$size = count($myLargerArray);
for( $j = 0; $j < $size; $j++ ) {
$myRecipientsObj->recipient_name = $myLargerArray[$j]['recipient_name'];
$myRecipientsObj->phone_number = $myLargerArray[$j]['phone_number'];

var_dump($myRecipientsObj); // This outputs the correct data added from [$j]

array_push($myObjArray->message_recipients, $myRecipientsObj);

var_dump($myObjArray->message_recipients); // The output shows array elements are being overwritten at each loop iteration
}

这是最后一个 var_dump($myObjArray->message_recipients) 的示例:
array(1) {
[0]=>
object(stdClass)#2 (2) {
["recipient_name"]=>
string(12) "First Person"
["phone_number"]=>
string(9) "112233445"
}
}
array(2) {
[0]=>
object(stdClass)#2 (2) {
["recipient_name"]=>
string(13) "Second Person"
["phone_number"]=>
string(9) "123456789"
}
[1]=>
object(stdClass)#2 (2) {
["recipient_name"]=>
string(12) "Second Person"
["phone_number"]=>
string(9) "123456789"
}
}
array(3) {
[0]=>
object(stdClass)#2 (2) {
["recipient_name"]=>
string(16) "Third Person"
["phone_number"]=>
string(9) "012345678"
}
[1]=>
object(stdClass)#2 (2) {
["recipient_name"]=>
string(16) "Third Person"
["phone_number"]=>
string(9) "012345678"
}
[2]=>
object(stdClass)#2 (2) {
["recipient_name"]=>
string(16) "Third Person"
["phone_number"]=>
string(9) "012345678"
}
}
array(4) {
... // it just overwriting the data with duplicates
}

我做错了什么导致这种情况,我该如何解决?

最佳答案

这是因为当你使用:

array_push($myObjArray->message_recipients, $myRecipientsObj);

您正在将对该对象的引用推送到数组中,然后当您在后续循环中更改对象时,您实际上更改了数组中每个元素的内容。要解决此问题,您需要将对象的副本推送到数组中:
array_push($myObjArray->message_recipients, clone $myRecipientsObj);

Demo on 3v4l.org

关于PHP array_push() 正在覆盖现有的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56187135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com