怎样使用php获取复杂json数据并输出,该如何解决

WBOY
Release: 2016-06-13 12:15:49
Original
982 people have browsed it

怎样使用php获取复杂json数据并输出
这是调用多客服查看当前在线客服时的微信api

返回数据示例(正确时的JSON返回结果):

{<br />    "kf_online_list": [<br />        {<br />            "kf_account": "[email&#160;protected]",<br />            "status": 1,<br />            "kf_id": "1001",<br />            "auto_accept": 0,<br />            "accepted_case": 1<br />        },<br />        {<br />            "kf_account": "[email&#160;protected]",<br />            "status": 1,<br />            "kf_id": "1002",<br />            "auto_accept": 0,<br />            "accepted_case": 2<br />        }<br />    ]<br />}
Copy after login


以下是我的代码:

$url_online ="https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token={$access_token}";<br />$output_online=file_get_contents($url_online);<br />$jsonStr = json_decode($output_online,true);<br />//读取信息:<br />$content = "客服1:".$jsonStr["kf_online_list"]["kf_account"]."\n在线状态:".$jsonStr["kf_online_list"]["status"]."\n正在接待人数:".$jsonStr["kf_online_list"]["accepted_case"]."\n\n客服2:".$jsonStr["kf_online_list"]["kf_account"]."\n在线状态:".$jsonStr["kf_online_list"]["status"]."\n正在接待人数:".$jsonStr["kf_online_list"]["accepted_case"];<br />?>
Copy after login


我本是希望获得所有的kf_account数据,并返回到微信回话界面,可是这结构有点复杂,还有相同的字段。。。
目前还查询不到结果,我估计是最后获取json的数组写的不对,希望大家帮忙!
------解决思路----------------------
$s =<<< JSON
{<br /> "kf_online_list": [<br /> {<br /> "kf_account": "[email&#160;protected]",<br /> "status": 1,<br /> "kf_id": "1001",<br /> "auto_accept": 0,<br /> "accepted_case": 1<br /> },<br /> {<br /> "kf_account": "[email&#160;protected]",<br /> "status": 1,<br /> "kf_id": "1002",<br /> "auto_accept": 0,<br /> "accepted_case": 2<br /> }<br /> ]<br />}
JSON;
$jsonStr = json_decode($s, true);

$content = '';
foreach($jsonStr['kf_online_list'] as $i=>$item) {
$n = $i + 1;
$content .= "
客服{$n}:$item[kf_account]
在线状态:$item[status]
正在接待人数:$item[accepted_case]
";
}
echo $content;
Copy after login
<br />客服1:[email&#160;protected]<br />在线状态:1<br />正在接待人数:1<br /><br />客服2:[email&#160;protected]<br />在线状态:1<br />正在接待人数:2<br /><br />
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template