'Cannot iterate over array after json_decode(file_get_contents(filename))

I want to write an Array as JSON into a file. Then i want to get the content, decode it and iterate over the array. The Problem is i cannot iterate over the Array that i get from the file. What am i doing wrong? var_dump() shows the array.

<?php

$array = array(
                array("Artikel" => "Bananen",
                        "Menge" => 10,
                        "id" => "4711"
                ),
                array("Artikel" => "Eier",
                        "Menge" => 1,
                        "id" => "abc"
                )
);

file_put_contents("daten.json", json_encode($array));


$array1 = json_decode(file_get_contents("daten.json"));

var_dump($array1);

for($i=0; $i<count($array1); $i++){
  echo $array1[$i]["Menge"];
  echo "<br>";
}
?>


Solution 1:[1]

If you run your code, you will get the error Cannot use object of type stdClass as array. This is because when json_encode is executed, the nested arrays are interpreted as an objects. If you write:

$array1 = json_decode(file_get_contents("daten.json"), true);

then the objects will be converted to arrays and everything will work as expected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitry Fedorov