php json解码

时间:2010-11-22 18:47:52

标签: php json

我正在尝试解码一些JSON并在MySQL中插入值。这是我的代码:

$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'];
}

我得到的错误是

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

1 个答案:

答案 0 :(得分:8)

true作为json_decode的第二个参数

$json_dec = json_decode($json,true);

否则它将返回一个对象而不是一个数组。

有关详细信息,请参阅此处:http://php.net/manual/en/function.json-decode.php