0

I'm trying to replace values from a json file with values submitted from a form. Json file is as following:

{
    "meta_titles": {
        "Just another site": "",
        "Test test": "",
        "This is a test post": "",
        "Hello world!": ""
    },
    "tag_titles": {
        "Title Test": "",
        "Recent Posts": "",
        "Recent Comments": "",
    }
}

And PHP array:

Array
(
    [meta_titles-0] => Juste un autre site Wordpress
    [meta_titles-1] => 
    [meta_titles-2] => Ceci est un test post
    [meta_titles-3] => Salut le monde
    [tag_titles-0] => 
    [tag_titles-1] => 
    [tag_titles-2] => 
)

Should return:

{
    "meta_titles": {
        "Just another site": "Juste un autre site Wordpress",
        "Test test": "",
        "This is a test post": "Ceci est un test post",
        "Hello world!": "Salut le monde"
    },
    "tag_titles": {
        "Title Test": "",
        "Recent Posts": "",
        "Recent Comments": "",
    }
}

What I have so far:

         $filecontent = file_get_contents($website_directory.'/'.$file_to_read);
         $oJson = json_decode($filecontent, true);

         foreach ($_POST as $key => $val) {
            foreach($oJson->fields as $i => $oVal) {
                    $oJson->fields[$i]->value = $val;
            }
         }
         $json = json_encode($oJson);
         var_dump($json);

Tried a lot of things but didn't find a way to do it. EDIT: I get the exact same content of the json file from var_dump.

2
  • What did you get from var_dump($json); ? Commented Apr 5, 2016 at 11:13
  • @TomaszTurkowski I get the exact same content of the json file from var_dump. Commented Apr 5, 2016 at 11:18

1 Answer 1

2
  • Second param from json_decode if set to true mean that $oJson will be array. So you will access $oJson like an array.
  • Your have to get the number from php array and search in json what key is at that position and update that key in the array. In json you have multi-level array and in $_POST you have only single level array.

You have to change to:

     $filecontent = file_get_contents($website_directory.'/'.$file_to_read);
     $oJson = json_decode($filecontent, true);

     foreach ($_POST as $key => $val) {
        list($json_key, $json_no) = explode("-", $key);
        $json_keys = array_keys($oJson[$json_key]);
        $oJson[$json_key][$json_keys[$json_no]] = $val;
     }
     $json = json_encode($oJson);
     var_dump($json);
Sign up to request clarification or add additional context in comments.

1 Comment

Damn Daniel!! Back at it again with the right answer! Thanks a lot, working perfectly like I want!

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.