如何用php解析这个json

时间:2012-01-31 12:27:57

标签: php json

我和json完全不相同。

我需要解析一个返回结果的json:

"response":{
    "status":1,
    "data":{
      "16":{
        "Offer":{
          "id":"16",
          "advertiser_id":null,
          "name":"My Offer",
          "description":null,
          "require_approval":"0",
          "require_terms_and_conditions":0,
          "terms_and_conditions":null,
          "offer_url":"http://",
          "preview_url":"http://",
        }
      },
      "17":{
        "Offer":{
          "id":"17",
          "advertiser_id":null,
          "name":"My Other Offer",
          "description":null,
          "require_approval":"0",
          "require_terms_and_conditions":0,
          "terms_and_conditions":null,
          "offer_url":"http://",
          "preview_url":"http://",
        }
      },
    },
    "errors":[]
  }

我需要访问所有商品名称,但我无法尝试访问:

$url = "jsonurl";

$string = file_get_contents($url);
$json_a=json_decode($string,true);

foreach ($json_a['data']['offer'] as $offer_a) {
  echo  $offer_a[name];
}

我做错了什么?

提前谢谢大家。

1 个答案:

答案 0 :(得分:3)

您似乎正在跳过16。但这样做很容易调试。

echo '<pre>';
print_r($json_a);
die();

这将在数组/对象中显示树。在这种情况下是一个数组。

但我想这会奏效:

foreach ($json_a['response']['data']['16']['Offer'] as $offer_a) {
  echo  $offer_a['name'];
}

如果您需要所有要约名称:

foreach ($json_a['response']['data'] as $offer){
    echo $offer['Offer']['name'];
}