0

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

1 Answer 1

1

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"}]
Sign up to request clarification or add additional context in comments.

1 Comment

this one already declare first and shows. [{name:"apple"}]; and how to add some object with value like the result i mention? [{name:"apple",city:"gotham"}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.