用PHP解析json数组
我一直在尝试解析json数组,但没有成功。我可以得到根元素,但不能得到任何数组元素。下面是我的来自Foursquare的json数组的开始,其中包含重复出现的元素用PHP解析json数组,php,arrays,json,Php,Arrays,Json,我一直在尝试解析json数组,但没有成功。我可以得到根元素,但不能得到任何数组元素。下面是我的来自Foursquare的json数组的开始,其中包含重复出现的元素 response: { keywords: {} suggestedRadius: 10000 headerLocation: "here" headerFullLocation: "here" headerLocationG
response: {
keywords: {}
suggestedRadius: 10000
headerLocation: "here"
headerFullLocation: "here"
headerLocationGranularity: "unknown"
headerMessage: "Suggestions for Friday evening"
totalResults: 214
groups: [
{
type: "Recommended Places"
name: "recommended"
items: [
{
reasons: {
count: 0
items: [ ]
}
venue: {
id: "4b799a05f964a520b1042fe3"
name: "Green Gables"
contact: {
phone: "3097472496"
formattedPhone: "(309) 747-2496"
}
location: {
address: "17485 East 2500 North Rd"
下面是我的PHP代码,试图获取餐厅的名称
$obj = json_decode($uri, true);
foreach($obj['response']['groups'] as $p)
{
if(isset($p['items']))
{
foreach($p['items'] as $p1)
{
if(isset($p1['venue']))
{
// echo varDumpToString($p1['venue']); // this dump works ok and shows the elements
foreach($p1['venue'] as $p2)
{
echo varDumpToString($p2['name']); // This is where I get the error
}
}
}
}
}
程序深入到name元素,然后给我一个错误,说“未定义索引:name”和“非法字符串偏移量name”。此消息出现14次,这是数组中每个项的一次。那么为什么“name”无法识别?
response.groups[x]。items[y].VICE
不是数组。您当前正试图访问响应.组[x]。项目[y]。场馆[z]。名称
,但您实际上正在访问响应.组[x]。项目[y].vention.id.name
,该名称不存在。最后一个foreach
迭代场馆属性,而不是场馆。每个项目只有一个场馆
它应该是这样的:
$obj = json_decode($uri, true);
foreach ($obj['response']['groups'] as $group) {
if (isset($group['items'])) {
foreach ($group['items'] as $item) {
if (isset($item['venue'])) {
echo varDumpToString($item['venue']['name']);
}
}
}
}
试着换一下这行
foreach($p1['venue'] as $p2)
到
当您使用json_decode()解码json时,您是否将其作为数组或对象返回?如果是对象,请尝试使用$p2->name。您是否确定节点已转换为
数组
,而不是stdObject
?在这种情况下,您可以通过$p2->name
LOL@AdrianCrepaz beat me to it访问该名称。这不会有任何帮助。$p2
将包含4B799A05F964A520B1042F
在第一种情况下,访问该字符串的name
属性没有多大意义。这正是OPs代码不起作用的原因。那么我的最后一个foreach应该是什么样的呢?我尝试了我能想到的所有组合。为什么我要访问vention.id.name。我认为id和name是独立的元素。我只想t id和名称作为单独的项。@Dave-查看我的示例。每个项只有一个位置,因此您不能对它们进行迭代。您还应该尝试为变量使用更多描述性名称以提高可读性。这使捕获类似错误变得容易得多。如果我使用“echo varDumpToString($p2['venu']['name']我会得到这个名字,但每个地点都会重复14次。我怎么才能得到单身者的名字呢?@Dave-我不知道你到底在做什么,但我怀疑以下几点:如果所有物品都在同一个地点,那么这个名字显然会被多次显示。@Equisive-非常感谢你的建议。效果很好!我是一个新手从wbie到PHP,我不可能找到我想要做的事情的例子。现在我知道了,我真的很感谢你的帮助。
foreach($p1['venue'] as $p2Key => $p2)