I am trying to change a PHP script so that it can recieve a JSON object and work with that given JSON object. Everything works fine until I try to cycle trhough the converted-from-JSON-array-of-objects (aka ‘stuff’) with the for loop.
What am I doing wrong here:
$json = '{
"foo": "hi",
"bar": "bye"
"stuff": [{"widget":"dd"},{"thing":"cc"},{"wcha":"dd"}]
}';
$arr = json_decode($json, true);
$foo = $arr['foo']; //works fine
$bar = $arr['bar']; //works fine
//old way that worked:
//$stuff = array("widget" => "dd", "thing" => "cc", "wcha" => "dd");
//new way that does not work:
$stuff = $arr['stuff'];
...
//This is where the problem is:
foreach ($stuff as $key => $value){...
The problem in the for loop is that $key is an integer (not the actual value) and $value is the word ‘Array’ (not the actual value).
It’s doing exactly what it should. The problem is that you’re not quite understanding it right.
“stuff” is an array of objects. So when you decode it, the resulting PHP array is this:
So when you call
foreachon it, you’re getting the individual arrays from there.I think your JSON should be:
Either that, or your PHP code should be: