Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add element to JSON object using PHP? [duplicate]

Tags:

json

php

I have this JSON array, and i want to add another value to it using PHP.

What would be the easiest way to add a ID and Name to this array using PHP.

 [
   {
      "id":1,
      "name":"Charlie"
   },
   {
      "id":2,
      "name":"Brown"
   },
   {
      "id":3,
      "name":"Subitem",
      "children":[
         {
            "id":4,
            "name":"Alfa"
         },
         {
            "id":5,
            "name":"Bravo"
         }
      ]
   },
   {
      "id":8,
      "name":"James"
   }
]
like image 709
sdfgg45 Avatar asked Jan 06 '16 12:01

sdfgg45


1 Answers

Simply, decode it using json_decode()

And append array to resulting array.

Again encode it using json_encode()

Complete code:

<?php
$arr = '[
   {
      "id":1,
      "name":"Charlie"
   },
   {
      "id":2,
      "name":"Brown"
   },
   {
      "id":3,
      "name":"Subitem",
      "children":[
         {
            "id":4,
            "name":"Alfa"
         },
         {
            "id":5,
            "name":"Bravo"
         }
      ]
   },
   {
      "id":8,
      "name":"James"
   }
]';
$arr = json_decode($arr, TRUE);
$arr[] = ['id' => '9999', 'name' => 'Name'];
$json = json_encode($arr);

echo '<pre>';
print_r($json);
echo '</pre>';
like image 78
Pupil Avatar answered Oct 21 '22 04:10

Pupil