我正在从URL中提取JSON数据,并试图显示一个仅显示名称的列表。
在某种程度上,如果我知道每次都会返回X个结果,这将是非常容易的循环。但是,返回的结果将从0到50+不等。
我做了很多搜索,都说“只要使用json_decode”.情况就没那么严重了。
我有以下JSON:
{
"ACK": "SUCCESS",
"ERROR": null,
"AGENT": {
"has_results": 1,
"agents": [
{
"display_name": "Alex",
"time_in_state": "5214",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "Bill",
"time_in_state": "6312",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "Carrie",
"time_in_state": "5982",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "David",
"time_in_state": "4226",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
}
]
},
"SKILL": {
"has_results": 1,
"num_skills": 1,
"skills": [
{
"display_name": "Phone Skills",
"skill_num": "76",
"callsinqueue": "0",
"callstoday": "9",
"abandtoday": "0",
"lwt": "0",
"ewt": "0",
"servicelvl": "100",
"avgspeedans": "6",
"talktime": "289"
}
]
},
"TIME": 1383766541
}根据我读过的示例和文档,创建了以下代码:
<?php
$url="http://myjsonurl.local";
$json = file_get_contents($url);
//echo $json;
$json = json_decode($json);
foreach($json as $item->display_name)
{
echo $item->agents->display_name;
}
?>我的最终目标是有一个名单的名称,然后我可以显示在一个备用网页。
所以我的问题是..。如何读取此页面并很好地格式化数据(也许可以打印一个数组)?这样我就可以在将来利用它了?
发布于 2013-11-07 17:52:30
您的代码中有以下内容:
foreach($json as $item->display_name) 这是不正确的,没有做你想做的事。通过执行print_r($json)可以看到,名称在$json->AGENT->agents中,因此您需要遍历这些项,然后使用箭头语法($item->display_name)遍历display_name。一旦您有了显示名称,就可以将其推入数组中,并任意使用它。
您的循环应该如下所示:
$names = array(); // initialize empty array
foreach($json->AGENT->agents as $item)
{
$names[] = $item->display_name;
}
print_r($names); // see the array contents输出:
Array
(
[0] => Alex
[1] => Bill
[2] => Carrie
[3] => David
)注意:如果事先不知道JSON对象的结构,那么可以使用嵌套的foreach循环来检索名称。
发布于 2013-11-07 17:50:30
要迭代的数组是$json->AGENT->agents。另外,您的foreach语法也是错误的。
尝试:
foreach($json->AGENT->agents as $item)
{
echo $item->display_name;
}发布于 2013-11-07 17:49:22
如果您希望将JSON数据作为数组而不是对象来获取,请使用json_decode($json, true)。这将告诉函数以关联数组的形式返回它,正如您可以在这里看到的:http://php.net/manual/en/function.json-decode.php
https://stackoverflow.com/questions/19842911
复制相似问题