I have the following script to get search results from an API and then slice the array and dump it, I am having trouble decoding the JSON into an array, it returns Arr
Separate your php from html please, use indentation and:
$array = json_decode($data, TRUE); //second param used for associative array return
Example #1 json_decode() examples
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
The above example will output:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
P.S: From the Bible (http://php.net/manual/en/function.json-decode.php)
Try json_decode
$array = json_decode($data, true);
Then you'll get an array instead of an object.
Example #1 json_decode() examples
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
The above example will output:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
If input is in array format then also you can use the same function json_decode. You just need to apply loop for result.
json = '{
"a1":{ "field1":"name1", "field2":age1, "field3":"country1" },
"a2":{ "field1":"name2", "field2":age2, "field3":"country2" },
"a3":{ "field1":"name3", "field2":age3, "field3":"country3" } }';
$Array = json_decode($json, true);
foreach ($Array as $key => $value)
{echo " $key "; foreach ($value as $k => $val) { echo "$k | $val <br />"; }
}