0

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?

3
  • 3
    Hi Clint, I'm not seeing that behaviour: 3v4l.org/YN073 Commented May 23, 2019 at 7:32
  • And it may be better to take $recipientsObj = new stdClass(); inside the loop (as local var in the loop scope Commented May 23, 2019 at 7:33
  • @Nick you're right - I just tracked down the bug to another section of the code where I'm doing an array_chunk that led to the issue in the question. Commented May 23, 2019 at 8:09

1 Answer 1

1

Tracked down the bug to a section of the code where I was performing an array_chunk on message_recipients and pushing the chunk to an array ($messageObj->message_recipients) leading to the issue in the question.

So I simply resolved it by equating $messageObj->message_recipients to the chunk instead of array_push() since it is already an array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.