php - How to update specific JSON object array inside JSON file?

I have a JSON object arrayabc_def_ghi
present in the json file../hello/xyz.json
. The content inside the json file is:
{
"abc_def_ghi": ["nada", "no", "yes", "nada", "nada", "no"],
"world_status": null
}
Below is how I am loading the json in my variable:
if (file_exists('../hello/xyz.json')) {
$data = json_decode(file_get_contents('../hello/xyz.json'));
}
I have a code below which is addding a default value (on specific condition) in the JSON object array. Now I need to overwrite my JSON file with this new content.
if ((date('j')==29)) {
$data->abc_def_ghi = array_fill(0, count($data->abc_def_ghi) , nada); // Line A
file_put_contents('../hello/xyz.json', $data);
}
Problem Statement:
I tried above code but somehow it is not overwriting my file but it deleted all the contents of the file.
After adding default value, my JSON should look like this in the file:
{
"abc_def_ghi": ["nada", "nada", "nada", "nada", "nada", "nada"],
"world_status": null
}
Answer
Solution:
You need tojson_encode
the data before you write it:
file_put_contents('../hello/xyz.json', json_encode($data));
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.