- 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);
$myObjArray->message_recipients = [];
for ($j = 0; $j < $size; $j++) {
$myRecipientsObj = new stdClass;
$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]
$myObjArray->message_recipients[] = $myRecipientsObj;
}
var_dump($myObjArray->message_recipients); // The output shows array elements are being overwritten at each loop iteration