Adding php variable to json object and decoding it NOT WORKS

Viewed 42

I have a json object like this:

$json_to_do = '{"name":"some_name", "phone_number":"0123456789"}';
$new_json = json_decode($json_to_do);
dd($new_json);

And the result is shown properly like this:

enter image description here

But now I need to assign some php variables as value like this:

$json_to_do = '{"name":'.$full_name.', "phone_number":"0123456789"}';

So the variable $full_name already exists there and if I dd($json_to_do), I correctly see this result:

"{"name":John, "phone_number":"0123456789"}"

But after decoding it, null results will be returned somehow:

$json_to_do = '{"name":'.$full_name.', "phone_number":"0123456789"}';
$new_json = json_decode($json_to_do);
dd($new_json); // returns null

So what's going wrong here? How can I properly assign php variables to the values of this json?

1 Answers

first you have to convert the json to array using json_decode , it will got the array , then u have to change the value

$json_to_do = '{"name":"some_name", "phone_number":"0123456789"}';
$new_json = json_decode($json_to_do , true);

$new_json['name'] = $your_variable_name;
Related