PHP array_push() is overwriting existing array elements

前端 未结 3 1934
栀梦
栀梦 2020-12-12 01:45

I\'m trying to push objects into an array to end up with an object array like this:

[
    {\"recipient_name\":\"John D\", \"phone_number\":\"123456\"},
    {         


        
相关标签:
3条回答
  • 2020-12-12 01:52

    You can directly write [] infront of message_recipients as below,

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

    It should work.

    Working demo

    0 讨论(0)
  • 2020-12-12 02:00
    $myObjArray->message_recipients[] = \DeepCopy\deep_copy($myRecipientsObj);
    
    0 讨论(0)
  • 2020-12-12 02:02

    It's because when you use:

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

    you are pushing a reference to the object into the array, and when you then change the object in subsequent passes through the loop, you effectively change the contents of each element of the array. To work around this, you need to push a copy of the object into the array instead:

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

    Demo on 3v4l.org

    0 讨论(0)
提交回复
热议问题