0
{
  "messages": [
    {
      "sender": "x",
      "message": "Placeholder",
      "date": "May 8, 2016 11:47:45 PM"
    }
    {
      "sender": "y",
      "message": "Yes",
      "date": "May 8, 2016 11:56:39 PM"
    },
    {
      "sender": "z",
      "message": "No",
      "date": "May 10, 2016 6:19:26 PM"
    }
  ]
}

What is the best practice to add object to messages array? Is there a standard way to do it?

2
  • 4
    Decode your json. Add the data. Encode it again. Commented Jun 6, 2016 at 18:43
  • $myJSON = json_decode($string, true); $myJSON['messages'][] = array('sender' => '', 'message' => '', 'date' => ''); $string = json_encode($myJSON); Commented Jun 6, 2016 at 18:46

1 Answer 1

0

It's pretty simple, just convert (decode) the JSON into a PHP array, add the new message data, and re-encode it to a JSON string!

Sample Code:

$array = json_decode($inputJSON);
$array['messages'][] = ['sender'=>'sample', 'message'=>'sample', 'date'=>'sample'];
$jsonOutput = json_decode($array);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.