我试图解码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_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "<pre>";
print_r($obj);

其他回答

这是一个后期的贡献,但是使用(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所指出的,性能可能会受到负面影响。

试着这样做:

$json_string = 'https://example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj->Result);
foreach($obj->Result as $value){
  echo $value->id; //change accordingly
}

这也会把它变成一个数组:

<?php
    print_r((array) json_decode($object));
?>

json_decode支持第二个参数,当它设置为TRUE时,它将返回一个数组而不是stdClass对象。查看json_decode函数的Manual页面,查看所有受支持的参数及其详细信息。

举个例子:

$json_string = 'http://www.example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, TRUE); // Set second argument as TRUE
print_r($obj['Result']); // Now this will works!

在PHP json_decode转换json数据到PHP相关数组 $php-array= json_decode($json-data, true); print_r ($ php数组);