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

时间:2019-05-17 13:11:41

标签: php arrays loops multidimensional-array array-push

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

'DA1234'

所以我要遍历更大的数组以获取名称和电话号码,并将它们作为对象推送到这样的数组中:

[
    {"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)

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

3 个答案:

答案 0 :(得分:5)

这是因为当您使用时:

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

您将对对象的引用推入数组,然后在随后的遍历循环中更改对象时,可以有效地更改数组中每个元素的内容。要解决此问题,您需要将对象的副本推入数组:

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

Demo on 3v4l.org

答案 1 :(得分:2)

您可以直接在message_recipients的前面写[],如下所示:

$myObjArray->message_recipients = [];
for ($j = 0; $j < $size; $j++) {
    $myRecipientsObj                 = new stdClass; // created std class object
    $myRecipientsObj->recipient_name = $myLargerArray[$j]['recipient_name'];
    $myRecipientsObj->phone_number   = $myLargerArray[$j]['phone_number'];
    $myObjArray->message_recipients[] = $myRecipientsObj;
}

应该可以。

工作demo

答案 2 :(得分:0)

$myObjArray->message_recipients[] = \DeepCopy\deep_copy($myRecipientsObj);