Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add another object with value in array

How to add another object with value in data?

Something start like :

$data=[{name:"apple"}]

And i wanted output like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$data=[{name:"apple",city:"gotham"}]

>Solution :

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"}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading