我试图解码JSON字符串到一个数组,但我得到以下错误。
致命错误:不能使用类型的对象
作为数组中的stdClass
C:\wamp\www\temp\asklaila.php联机
6
代码如下:
<?php
$json_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj['Result']);
?>
根据文档,如果您想要一个关联数组而不是来自json_decode的对象,则需要将true指定为第二个参数。代码如下:
$result = json_decode($jsondata, true);
如果你想要整型键而不是属性名:
$result = array_values(json_decode($jsondata, true));
然而,在你当前的解码中,你只是将它作为一个对象访问:
print_r($obj->Result);
这是一个后期的贡献,但是使用(array)强制转换json_decode是有效的。
考虑以下几点:
$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
echo $v; // etc.
}
如果$jsondata作为空字符串返回(在我的经验中经常是这样),json_decode将返回NULL,导致错误Warning:在第3行为foreach()提供了无效参数。你可以添加一行if/then代码或三元操作符,但在我看来,简单地将第2行更改为…
$arr = (array) json_decode($jsondata,true);
... 除非您同时对数百万个大型数组进行json_decode,在这种情况下,如@TCB13所指出的,性能可能会受到负面影响。
根据PHP文档,json_decode函数有一个名为assoc的参数,它将返回的对象转换为关联数组
mixed json_decode ( string $json [, bool $assoc = FALSE ] )
由于assoc参数默认为FALSE,您必须将此值设置为TRUE才能检索数组。
检查下面的代码的示例含义:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
输出:
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)
}
我希望这对你有所帮助
$json_ps = '{"courseList":[
{"course":"1", "course_data1":"Computer Systems(Networks)"},
{"course":"2", "course_data2":"Audio and Music Technology"},
{"course":"3", "course_data3":"MBA Digital Marketing"}
]}';
使用Json解码函数
$json_pss = json_decode($json_ps, true);
在php中循环JSON数组
foreach($json_pss['courseList'] as $pss_json)
{
echo '<br>' .$course_data1 = $pss_json['course_data1']; exit;
}
结果:电脑系统(网络)