How to add element to JSON object using PHP?

Simply, decode it using json_decode()

And append array to resulting array.

Again encode it using json_encode()

Sample code:

<?php
$arr = '[
   {
      "id":1,
      "name":"Abdul"
   },
   {
      "id":2,
      "name":"Rupesh"
   },
   {
      "id":3,
      "name":"Rabiya",
      "children":[
         {
            "id":4,
            "name":"Child1"
         },
         {
            "id":5,
            "name":"Child2"
         }
      ]
   },
   {
      "id":8,
      "name":"Mohammad"
   }
]';
$arr = json_decode($arr, TRUE);
$arr[] = ['id' => '9999', 'name' => 'New Name'];
$json = json_encode($arr);

echo '<pre>';
print_r($json);
echo '</pre>';

?>

Output:

  [
     {"id":1,"name":"Abdul"},
     {"id":2,"name":"Rupesh"},
     {"id":3,"name":"Rabiya","children":[
                                         {"id":4,"name":"Child1"},
                                         {"id":5,"name":"Child2"}]
     },
     {"id":8,"name":"Mohammad"},
     {"id":"9999","name":"New Name"}
    ]

Leave a Reply

Your email address will not be published.