3天前我提出了这个问题,但是到目前为止,我无法解决我的问题。我将再次提出问题,希望有人帮助我。
我有以下JSON结构
{"Id":"1","Persons":[{"Name":"Luis","Time":"00:00:09","info":"","Timeext":"","Timeout":"","Timein":""}, {"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""},{"Name":"Ben","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}]}
要访问元素Id
不是问题。我可以得到这样的价值:
$arr['Id'] = $_POST['Id'];
echo $arr['Id'];
但是如果想要访问JSON内部的结构Persons
,特别是每个Person的Time值,我喜欢这样:
$arr['Persons'] = $_POST['Persons'];
$jsdecode = json_decode($arr['Persons']);
foreach ($arr['Persons'] as $p){
echo "$p->Time <br/>";
}
这是得到的结果:
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>38</b><br />
<br />
<b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>41</b><br />
<br/><br />
<b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>41</b><br />
<br/>
请问有人帮助我吗?
答案 0 :(得分:2)
json_encode() - PHP数组到JSON
json_encode()
方法将采用PHP数组并将其编码为JSON,以供AJAX调用使用。
$myarray = array('Guitar' => 'Johnny', 'Vocals'=> 'Stephen', 'Bass' => 'Andy', 'Drums' => 'Mike');
$myJson = json_encode($myarray);
echo $myJson;
json_decode() - JSON到PHP数组
json_decode()
将获取JSON并将其转换为PHP数组。
$myJson = '{"Guitar" : "Johnny", "Vocals": "Stephen", "Bass" : "Andy", "Drums" : "Mike"}';
$myarray = json_decode($myJson, true);
print_r($myarray);
答案 1 :(得分:1)
您遇到语法错误:
{"Id":"1","Persons":[
{"Name":"Luis","Time":"00:00:09","info":"","Timeext":"","Timeout":"","Timein":""},
{"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""},
{"Name":"Luis","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}
]}
在Name Louis之前没有逗号。
您应始终在http://jsonlint.com/
上验证已编码的json