I'm looping over some data and dynamically creating an object which I want to push into an array.
$messageObj = new stdClass(); $recipientsObj = new stdClass();
$messageObj->message_recipients = Array();
$size = count($results);
for( $j = 0; $j < $size; $j++ ) {
$recipientsObj->recipient_name = $results[$j]['recipient_name'];
$recipientsObj->phone_number = $results[$j]['phone_number'];
var_dump(json_encode($recipientsObj)); // DUMP 1
array_push($messageObj->message_recipients, clone $recipientsObj);
var_dump($messageObj->message_recipients); // DUMP 2
}
PROBLEM
// DUMP 1 outputs the expected data - for instance
string(55) "{"recipient_name":"JOHN DOE","phone_number":"123456789"}"
But when I push the object into the array, the object is pushed as an array so I get:
[ [{...}], [{...}], [{...}] ] // DUMP 2
instead of
[ {...}, {...}, {...} ]
What could be causing this? Am I pushing it the wrong way?
$recipientsObj = new stdClass();inside the loop (as local var in the loop scopearray_chunkthat led to the issue in the question.