我试图将JSON字符串解码为数组,但我收到以下错误.
致命错误:不能在第6行的C:\ wamp\www\temp\asklaila.php中使用stdClass类型的对象作为数组
这是代码:
<?php
$json_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj['Result']);
?>
Run Code Online (Sandbox Code Playgroud)
Ste*_*hen 807
根据文档,您需要指定是否需要关联数组而不是对象json_decode,这将是代码:
json_decode($jsondata, true);
Run Code Online (Sandbox Code Playgroud)
diE*_*cho 44
试试这个
$json_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "<pre>";
print_r($obj);
Run Code Online (Sandbox Code Playgroud)
neo*_*kio 26
这是一个迟到的贡献,但对于投出有效的情况下json_decode用(array).
考虑以下:
$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
echo $v; // etc.
}
Run Code Online (Sandbox Code Playgroud)
如果$jsondata作为一个空字符串返回(根据我的经验,它经常是),json_decode将返回NULL,导致错误警告:为第3行的foreach()提供的无效参数.您可以添加一行if/then代码或三元运算符,但IMO更简洁,只需将第2行更改为......
$arr = (array) json_decode($jsondata,true);
Run Code Online (Sandbox Code Playgroud)
......除非您同时使用json_decode数百万个大型阵列,在这种情况下,@ TCB13指出,性能可能会受到负面影响.
小智 6
这也会将其更改为数组:
<?php
print_r((array) json_decode($object));
?>
Run Code Online (Sandbox Code Playgroud)
根据PHP Documentation json_decode函数,有一个名为assoc的参数,它将返回的对象转换为关联数组
mixed json_decode ( string $json [, bool $assoc = FALSE ] )
Run Code Online (Sandbox Code Playgroud)
由于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));
Run Code Online (Sandbox Code Playgroud)
输出:
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)
}
Run Code Online (Sandbox Code Playgroud)
json_decode($data, true); // Returns data in array format
json_decode($data); // Returns collections
Run Code Online (Sandbox Code Playgroud)
因此,如果想要一个数组,您可以在json_decode函数中将第二个参数作为“true”传递。