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\"},
{
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
$myObjArray->message_recipients[] = \DeepCopy\deep_copy($myRecipientsObj);
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