简体   繁体   中英

How Can I Add Data to Array In JSON \w PHP?

I've json file like this.

{
  "id": 22,
  "sender": "btknctTR",
  "title": "(Sistem) btknctTR - Son mesajları.",
  "date": "May 8, 2016 4:46:13 PM",
  "lastupdatedate": "May 12, 2016 5:43:30 PM",
  "category": "Küfür_Bildirimi",
  "priority": "Normal",
  "appointedAdmin": "DonduranAtes",
  "archived": true,
  "messages": [
    {
      "sender": "btknctTR",
      "message": "asd",
      "date": "May 8, 2016 11:47:45 PM"
    },
    {
      "sender": "btknctTR",
      "message": "/asd",
      "date": "May 8, 2016 11:47:46 PM"
    },
    {
      "sender": "btknctTR",
      "message": "/report btknctTR",
      "date": "May 8, 2016 11:47:51 PM"
    },
    {
      "sender": "Speaw",
      "message": "tamam",
      "date": "May 8, 2016 11:56:39 PM"
    },
    {
      "sender": "KaptanUcar",
      "message": "peki",
      "date": "May 10, 2016 6:19:26 PM"
    }
  ]
}

I want to add a new message to "messages" array and convert string to json. This is a support system. How can I do it?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM