Reputation: 49
How to add another object with value in data?
Something start like :
$data=[{name:"apple"}]
And i wanted output like this
$data=[{name:"apple",city:"gotham"}]
Upvotes: 0
Views: 38
Reputation: 94662
Dont try and build JSON manually, create a PHP data structure that you want and then use json_encode()
to make it into a JSON String
$d = [(object)['name' => 'apple', 'city' => 'gotham']];
echo json_encode($d);
RESULT
[{"name":"apple","city":"gotham"}]
If some values already exists, you should decode it to a PHP data struture and then add to it and convert back to JSON String
$data='[{"name":"apple"}]';
$d = json_decode($data);
$d[0]->city = 'Gotham';
$data = json_encode($d);
RESULT
[{"name":"apple","city":"Gotham"}]
Upvotes: 1