Перебрать проанализированную строку JSON в PHP - PullRequest
1 голос
/ 12 мая 2011

У меня сложная структура, возвращаемая URL в формате JSON, у меня есть ответ, который я могу просмотреть через var_dump, Теперь у меня есть этот ответ,

{
  "groups": [],
  "total_pages": 1,
  "spots": [
    {
      "address": {
        "region": "TX",
        "locality": "Austin"
      },
      "name": "Dirty Bill's",
      "checkins_count": 646,
      "_image_url_200": "http://static.gowalla.com/categories/28-b0d41920d32839ce1ecd6641e5fc2c87-200.png",
      "image_url": "http://static.gowalla.com/categories/28-78c9b4d7d239784df49dc932f64a3519-100.png",
      "_image_url_50": "http://static.gowalla.com/categories/28-78c9b4d7d239784df49dc932f64a3519-100.png",
      "radius_meters": 50,
      "trending_level": 0,
      "users_count": 375,
      "url": "/spots/43711",
      "checkins_url": "/checkins?spot_id=43711",
      "lng": "-97.7495040214",
      "spot_categories": [
        {
          "name": "Dive Bar",
          "url": "/categories/28"
        }
      ],
      "foursquare_id": null,
      "highlights_url": "/spots/43711/highlights",
      "items_url": "/spots/43711/items",
      "items_count": 11,
      "strict_radius": false,
      "description": "AKA the Gnome Bar. Much Warmer than Key Bar.",
      "activity_url": "/spots/43711/events",
      "lat": "30.2696322356",
      "photos_count": 23
    },
    {
      "address": {
        "region": "TX",
        "locality": "Austin"
      },
      "name": "Austin Wellness Clinic",
      "checkins_count": 1,
      "_image_url_200": "http://static.gowalla.com/categories/118-b41c2ba96f1ffe99fc23f12f0ee3b960-200.png",
      "image_url": "http://static.gowalla.com/categories/118-5f9e72162abf3dcbc0108cdbdba6a29f-100.png",
      "_image_url_50": "http://static.gowalla.com/categories/118-5f9e72162abf3dcbc0108cdbdba6a29f-100.png",
      "radius_meters": 75,
      "trending_level": 0,
      "users_count": 1,
      "url": "/spots/7360448",
      "checkins_url": "/checkins?spot_id=7360448",
      "lng": "-97.7495133877",
      "spot_categories": [
        {
          "name": "Health & Fitness",
          "url": "/categories/118"
        }
      ],
      "foursquare_id": null,
      "highlights_url": "/spots/7360448/highlights",
      "items_url": "/spots/7360448/items",
      "items_count": 0,
      "strict_radius": false,
      "description": null,
      "activity_url": "/spots/7360448/events",
      "lat": "30.2695755256",
      "photos_count": 0
    },

Я использовал json_decode ($ответ, правда), чтобы получить переменную синтаксического анализа, теперь я не уверен, как его перебрать.Есть идеи?!

edit 1: Spot - это массив [] с индексом 0. Я хочу зациклить каждую пару имен-значений внутри массива spot

Ответы [ 4 ]

3 голосов
/ 12 мая 2011
<?php

$json = json_encode(
    array(
        'spots' => array(
            'bar' => 'baz',
            array(
                'quz' => 'foo',
                'bar' => 'baz'
            )
        )
    )
);

$root = json_decode( $json, true );

function read( $array ) {
    foreach( (array) $array as $key => $value ) {
        if( is_array( $value ) ) {
            read( $array );
        }
        echo "$key = $value\n";
    }
}

foreach( $root['spots'] as $spot ) {
    read( $spot );
}

Это должно дать вам всю информацию в массиве spot.

EDIT : Теперь с фактически проверенным синтаксисом все работает.

2 голосов
/ 12 мая 2011

Или попробуйте это:

$result = json_decode($response,true);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($result));
foreach($iterator as $key=>$value) {
        echo "<b>".$key."</b><br />".$value."<br />";
}

Это преобразует сложный ассоциативный массив в простой массив для зацикливания.Надеюсь, это поможет.

2 голосов
/ 12 мая 2011
$result = json_decode($response,true);

foreach($result['spots'] as $spot)
{
    echo $spot['address']['locality'];
}
0 голосов
/ 12 мая 2011

Вы бы не прошли через это, вы бы использовали рекурсию , чтобы пройти через это.Вам необходимо написать функцию, которая может вызывать себя, передавая различные ветви этой структуры себе в качестве аргументов. может помочь вам с рекурсией PHP.

...