[英]How to parse a json array?
我一直試圖解析一個json數組,但沒有成功。 我可以得到一個根元素,但不能得到任何數組元素。 以下是來自Foursquare的json數組的開頭,該數組具有重復出現的場所元素。
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代碼,用於嘗試獲取餐廳名稱。
$uri = file_get_contents("https://api.foursquare.com/v2/venues/explore?ll=40.7,-89&oauth_token=xxxxxxxxx", true);
$obj = json_decode($uri, true);
foreach($obj['response']['groups']['items']['venue'] as $p)
{']
if(isset($p['name))
echo $p['name'];
}
執行此代碼時,我收到一條錯誤消息:“無效的索引:地點。 如果我只使用foreach($ obj ['response'] ['groups']作為$ p),我會得到結果。 因此,這與確定組下元素的名稱有關。
好。 這是我最新的PHP代碼。 它向下鑽取到name元素,然后給我一個錯誤消息:“ Unefined index:name”和“ Illegal string offset name”。此消息出現14次,這是數組中每個項的一次。所以為什么是“ name” ”“沒認錯嗎?有什么想法。
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
}
}
}
}
}
因為您將JSON對象解析為PHP數組( json_decode
的第二個參數),但是,您正在訪問結果就好像它是一個對象一樣。
使用數組下標訪問元素( $obj['response']['groups']['items']['venue']
),或解析為對象( json_decode($uri, false)
或json_decode($uri)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.