0

I have a JSON object array abc_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
}

1 Answer 1

1

You need to json_encode the data before you write it:

file_put_contents('../hello/xyz.json', json_encode($data));
Sign up to request clarification or add additional context in comments.

2 Comments

@john: Try it and you tell me
@Every Hi, I hope all is well. I have one more question. It's not similar. I am wondering if you can have a look.

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.