- array_push: documentation ( source)
- var_dump: documentation ( source)
- json_decode: documentation ( source)
<?php
$json = '[
{"recipient_name":"John D", "phone_number":"123456"},
{"recipient_name":"Doe J", "phone_number":"654321"},
{"recipient_name":"Jon Do", "phone_number":"112233"}
]';
$myLargerArray = json_decode($json, true);
$myObjArray = (object)['message_recipients' => 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, clone $myRecipientsObj);
var_dump($myObjArray->message_recipients); // The output shows array elements are being overwritten at each loop iteration
}