나는 성공없이 json 배열을 파싱하려고 노력해왔다. 루트 요소는 얻을 수 있지만 배열 요소는 얻을 수 없습니다. 아래는 Foursquare의 json 어레이가 다시 시작되는 장소입니다.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 요소까지 드릴 다운 한 다음 "Unfinished index : name"및 "Illegal string offset name"오류 메시지를 표시합니다.이 메시지는 배열의 각 항목에 대해 한 번씩 14 번 나타납니다. 당신이 PHP 배열과 JSON 개체 (json_decode
의 두 번째 매개 변수)를 분석하고 있기 때문에 "
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이 아닙니다. (누락 된 쉼표, 누락 된 외부 수준 parens, ...) – knittl
foreach ($ obj [ '응답'] [그룹 '] ['항목 '] ['장소 '] $ p로) foreach를 변경했습니다. 내가 바꿀 것을 제안 하는가? – Dave
게시 한 응답이 유효한 JSON이 아니므로 json_decode가 작동하지 않습니다. 불완전하게 게시했다면,'var_dump'를 사용하여 디코딩 된 객체를보고 올바른 첨자를 파생시킬 수 있습니다. – knittl