Michael Michael - 3 months ago 10
JSON Question

php json decode

I'm trying to decode some JSON and insert the values in MySQL. Here is my code:

$json = '
{"d":[{"Id":1059,"Name":"Alfa Romeo - 145"},{"Id":20020,"Name":"Alfa Romeo - 146"},{"Id":1060,"Name":"Alfa Romeo - 147"},{"Id":20021,"Name":"Alfa Romeo - 155"},{"Id":1061,"Name":"Alfa Romeo - 156"},{"Id":20022,"Name":"Alfa Romeo - 159"},{"Id":20023,"Name":"Alfa Romeo - 164"},{"Id":20024,"Name":"Alfa Romeo - 166"},{"Id":20025,"Name":"Alfa Romeo - 33"},{"Id":20026,"Name":"Alfa Romeo - Brera"},{"Id":20027,"Name":"Alfa Romeo - GT"},{"Id":20028,"Name":"Alfa Romeo - GTV"},{"Id":239,"Name":"Alfa Romeo - Misc"},{"Id":20029,"Name":"Alfa Romeo - Spider"},{"Id":20030,"Name":"Alfa Romeo - Sportwagon"}]}
';

$json_dec = json_decode($json);

$nr = 0;
while($nr 14) {
$id_nr = $json_dec['d']['$nr']['Id'];
$make = $json_dec['d']['$nr']['Name'];
}


The error that I get is

Fatal error: Cannot use object of type stdClass as array in
C:\wamp\www\get_cat.php on line 18

Answer

Put true as second argument for json_decode

$json_dec = json_decode($json,true);

Otherwise it will return an object instead of an array.

See here for more information: http://php.net/manual/en/function.json-decode.php