Home > Net >  how to add another object with value in array
how to add another object with value in array

Time:11-26

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"}]

CodePudding user response:

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"}]

CodePudding user response:

You should use the json object format: '[{"name":"value"}]' then use json_decode to convert it from string to json object.

$data = '[{"name":"apple"}]';
$data = json_decode($data);
$data[] = array('city' => 'gotham');
$data = json_encode($data);
echo $data;

OUTPUT:

[{"name":"apple"},{"city":"gotham"}]
  • Related