PHP array_push() is overwriting existing array elements

前端 未结 3 1946
栀梦
栀梦 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

提交回复
热议问题