2

I have a JSON object in a file called info.json that looks like this -->

[
    {
        "name": "level0",
        "items": 
            [
                {
                    "name": "item1",
                    "type": "type1"
                },
                {
                    "name": "item2",
                    "type": "type2"
                }

            ]
    },
    {
        "name": "Level1",
        "items":
            [
                {
                    "name": "item4",
                    "type": "type4"
                },
                {
                    "name": "item5",
                    "type": "type5"
                }
            ]
    },
    {
        "name": "Level2",
        "items":
            [
                {
                    "name": "item6",
                    "type": "type6"
                }

            ]
    }
]

and a php script that looks like this -->

<?php

    $json_string = file_get_contents("info.json");
    $json = json_decode($json_string, true);

    array_push($json[0]["items"], array("name" => "item3", "type" => "type3"));
?>

I'm trying to insert a third element in the first instance of "items" in this array, such that when I open the JSON file the new element will appear. What am I doing wrong? Any advice would be appreciated, thanks.

LF00
  • 27,015
  • 29
  • 156
  • 295
laroy
  • 163
  • 1
  • 1
  • 13

3 Answers3

1

Your code looks fine to me. Output the $json variable and you will be able to see your desired result.

print(json_encode($json, JSON_PRETTY_PRINT));

I made a sample for you: https://eval.in/818486

Hope this helps :)

Sahan Serasinghe
  • 1,591
  • 20
  • 33
1

After you have changed the $json array, you need to save it to your info.json file with this,

file_put_contents("info.json", json_encode($json));
LF00
  • 27,015
  • 29
  • 156
  • 295
0

Hello laroy you have not right the new json encode string to the file so your code will look like this

<?php

$json_string = file_get_contents("info.json");
$json = json_decode($json_string, true);
array_push($json[0]["items"], array("name" => "item3", "type" => "type3"));
$strNew = json_encode($json);
file_put_contents("info.json", $strNew);

?>

Now you can check the the info.json file.

Darshan ambaliya
  • 301
  • 3
  • 20