我试图解码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']);
?>

当前回答

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

根据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; 

}

结果:电脑系统(网络)

试着这样做:

$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
}

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!