用 PHP 解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6964403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:41:43  来源:igfitidea点击:

Parsing JSON with PHP

phparraysjson

提问by csm232s

I'm attempting to pull in data from Google's Shopping API. I'm able to download the data successfully, but I'm having trouble parsing through it with PHP. I'm still learning, but I seem to be having issues with multi-dimensional arrays. I capture the JSON with $json = json_decode($data);.

我正在尝试从 Google 的 Shopping API 中提取数据。我能够成功下载数据,但我无法使用 PHP 解析它。我仍在学习,但我似乎遇到了多维数组的问题。我用$json = json_decode($data);.

The following just echos the outer array, but I can't pull from the inner array:

以下只是呼应外部数组,但我无法从内部数组中提取:

foreach($json as $key => $value) {
  echo $key . " : " . $value;
}

If I want to grab the "title", "description", "brand", and "availability" for each product, how would I parse through it?

如果我想抓取每个产品的“标题”、“描述”、“品牌”和“可用性”,我将如何解析它?

{
 "kind": "shopping#products",
 "etag": "\"T9uPnY2MZMB71TDpKXXZdr3yWX4/qtJ5vmpftFWNfijyLD9ti2Xpj-w\"",
 "id": "tag:google.com,2010:shopping/products",
 "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d2",
 "nextLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d5",
 "previousLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d1",
 "totalItems": 633694,
 "startIndex": 2,
 "itemsPerPage": 3,
 "currentItemCount": 3,
 "items": [
  {
   "kind": "shopping#product",
   "id": "tag:google.com,2010:shopping/products/1161353/11882813508247586172",
   "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1161353/gid/11882813508247586172",
   "product": {
    "googleId": "11882813508247586172",
    "author": {
     "name": "Buy.com",
     "accountId": "1161353"
    },
    "creationTime": "2011-04-24T05:13:38.000Z",
    "modificationTime": "2011-08-05T17:45:24.000Z",
    "country": "US",
    "language": "en",
    "title": "Sony BRAVIA KDL-46EX720 46 inch 3D LED HDTV 1080p 120Hz",
    "description": "Entertainment lovers the slim Sony EX720-Series LED HDTV is for you. See precise motion detail plus watch your favorite 2D or 3D entertainment in clear, vivid Full HD 1080p picture quality with incredible contrast. You can even connect to the internet and access a great selection of online entertainment with Netflix , Hulu Plus , Pandora , Qriocity and more - there s always something on. Plus video chat with friends and family when you Skype on the big screen.",
    "link": "http://clickfrom.buy.com/default.asp?adid\u003d17902&sURL\u003dhttp%3A%2F%2Fwww.buy.com%2Fprod%2Fsony-bravia-kdl-46ex720-46-3d-led-hdtv-1080p-120hz%2Fq%2Fsellerid%2F10004001%2Floc%2F111%2F219891693.html",
    "brand": "Sony",
    "condition": "new",
    "gtin": "00027242817081",
    "gtins": [
     "00027242817081"
    ],
    "inventories": [
     {
      "channel": "online",
      "availability": "inStock",
      "price": 1348.0,
      "currency": "USD"
     }
    ],
    "images": [
     {
      "link": "http://ak.buy.com/PI/0/1000/219891693.jpg"
     }
    ]
   }
  },
  {
   "kind": "shopping#product",
   "id": "tag:google.com,2010:shopping/products/7827/1976288072671326122",
   "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/7827/gid/1976288072671326122",
   "product": {
    "googleId": "1976288072671326122",
    "author": {
     "name": "Dell",
     "accountId": "7827"
    },
    "creationTime": "2011-06-08T15:11:49.000Z",
    "modificationTime": "2011-08-05T15:04:13.000Z",
    "country": "US",
    "language": "en",
    "title": "Sony Bravia 55\" KDL55EX500 1080p 120Hz LCD HDTV",
    "description": "Enjoy breathtaking viewing experience with Bravia 55-inch KDL55EX500 1080p LCD HDTV from Sony?. This LCD TV features Motionflow? 120 Hz Technology that allows you to experience smooth motion detail and clarity which delivers a crisp, fluid and realistic viewing skill during fast-action scenes. Additionally, the incorporated LightSensor? Technology automatically increases or decreases the level of brightness of your TV's backlight based on a room's lighting conditions. Moreover, the BRAVIA Engine? 2 fully processor lets you enjoy sharp, vibrant, life-like images while optimizing color, contrast and significantly reducing noise. Besides this, get a natural looking picture with an Ambient Sensor. Plus, you can also share your photos and music on the big screen by simply connecting your digital camera, USB-enabled MP3 player, or USB storage device directly to your HDTV's USB input. With all these features loaded into a single television the Bravia EX500 is an ideal choice to complement your digital lifestyle.var wcCpi\u003d\"A3477150\";",
    "link": "http://lt.dell.com/lt/lt.aspx?CID\u003d27530&LID\u003d627063&DGC\u003dSS&DGSeg\u003dDHS&DURL\u003dhttp://accessories.us.dell.com/sna/productdetail.aspx?c\u003dus%26l\u003den%26s\u003ddhs%26cs\u003d19%26sku\u003dA3477150%26CAWELAID\u003d469727188",
    "brand": "Sony",
    "condition": "new",
    "gtin": "00027242784932",
    "gtins": [
     "00027242784932"
    ],
    "inventories": [
     {
      "channel": "online",
      "availability": "inStock",
      "price": 1348.0,
      "currency": "USD"
     }
    ],
    "images": [
     {
      "link": "http://accessories.us.dell.com/sna/images/products/large/A3477150temp.jpg"
     }
    ]
   }
  },
  {
   "kind": "shopping#product",
   "id": "tag:google.com,2010:shopping/products/1113342/9429326904502109794",
   "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1113342/gid/9429326904502109794",
   "product": {
    "googleId": "9429326904502109794",
    "author": {
     "name": "Walmart",
     "accountId": "1113342"
    },
    "creationTime": "2011-03-26T23:58:51.000Z",
    "modificationTime": "2011-08-04T19:42:49.000Z",
    "country": "US",
    "language": "en",
    "title": "Sony Bravia 32\" Class 3D LED-LCD 1080p 240Hz HDTV,1.68\" ultra-Slim,",
    "description": "Note: You must have a source of HD programming in order to take full advantage of the Sony Bravia 32\" Class 3D 1080p LED HDTV. Contact your local cable or satellite TV provider for details on how to upgrade.Visit the Sony Brand Shop for 3D glasses, other 3D HDTVs and more.Sony Bravia 32\" Class 3D 1080p LED HDTV 240Hz, KDL-32EX720:See It All In 3D: Engineered with advanced technologies, the EX720 Series is more than a fully-loaded HDTV with 3D. Once you slide on the active shutter glasses (sold separately), the on-screen image is precisely synchronized and delivered with the Full HD image intact for an immersive entertainment viewing experience with maximum resolution and superb clarity.Slim Design, Stunning Picture: Experience the next level of picture quality and contrast with Edge LED Backlight technology. U",
    "link": "http://www.walmart.com/ip/Sony-KDL-32EX720/15780230?sourceid\u003d1500000000000003142050&ci_src\u003d14110944&ci_sku\u003d15780230",
    "brand": "Sony",
    "condition": "new",
    "gtin": "00027242817135",
    "gtins": [
     "00027242817135"
    ],
    "inventories": [
     {
      "channel": "online",
      "availability": "inStock",
      "price": 898.0,
      "currency": "USD"
     }
    ],
    "images": [
     {
      "link": "http://i.walmartimages.com/i/p/00/02/72/42/81/0002724281713_500X500.jpg"
     }
    ]
   }
  }
 ]
}

采纳答案by brian_d

Your JSON is a mix of arrays and objects. So array notation will not work for all items. For example, to find the brand use:

您的 JSON 是数组和对象的混合。因此数组表示法不适用于所有项目。例如,要查找品牌使用:

foreach ($json->items as $item) {
   var_dump($item->product->brand);
}

Codepad example
JSON specification

键盘示例
JSON 规范

回答by rahlstrom

If I was you, I would parse the JSON as an array instead of as an object. This can be done by doing the following:

如果我是你,我会将 JSON 解析为数组而不是对象。这可以通过执行以下操作来完成:

$json = json_decode($data, true);

By included the second argument in json_decode with a value of true, you get back an array. You can then do something like:

通过在 json_decode 中包含值为 true 的第二个参数,您将返回一个数组。然后,您可以执行以下操作:

echo '<pre>';
print_r($json);
exit;

This will give you an idea of the array structure of the data and how to access the information you want. For example, to pull the title, brand, and description of each item, you'd do the following:

这将使您了解数据的数组结构以及如何访问所需的信息。例如,要提取每个项目的标题、品牌和描述,您需要执行以下操作:

foreach($json['items'] as $item) {
    echo 'Title: ' . $item['product']['title'] . '<br />';
    echo 'Brand: ' . $item['product']['brand'] . '<br />';
    echo 'Description: ' . $item['product']['description'] . '<br />';
}

To get the availability, again do a dump of the array using print_r() and figure out the best way to access it from the array.

为了获得可用性,再次使用 print_r() 对数组进行转储,并找出从数组访问它的最佳方法。

回答by Suryavel TR

We can parse JSON Arraylike this,

我们可以像这样解析JSON 数组

<?php
$json = "[{\"name\":\"user1\",\"id\":\"940\"},{\"name\":\"user2\",\"id\":\"949\"}]";
$dec = json_decode($json);

for($idx = 0; $idx < count($dec); $idx++){
    $obj = (Array)$dec[$idx];
    echo $obj["name"];
}
?>

and similarly JSON Objectlike this,

和类似的JSON 对象

<?php
$json = "{\"name\":\"user1\",\"id\":\"940\"}";
$dec = (Array)json_decode($json);

echo $dec["name"];
?>

回答by Yuvraj Singh Chouhan

You can use this json parserfor seeing your content in proper format.

您可以使用此 json 解析器以正确的格式查看您的内容。

You can use this code:

您可以使用此代码:

$json = json_decode($url,true);

//you can retrieve kind, tag, id by using

$kind = $json['kind'];
$id = $json['id'];

Here, items itself will have an array that you can use this

在这里,项目本身将有一个数组,您可以使用它

$items[] = $json['items'];

// you can retrieve the data inside the kind array

$kind_arr = $json['items'][0][]['kind'];

//similarly you can parse all the data

回答by Jasmeen

 $json = '{ "a1":{ "field1":"name1", "field2":age1, "field3":"country1"
 }, 

 "a2":{ "field1":"name2", "field2":age2, "field3":"country2" },

  "a3":{ "field1":"name3", "field2":age3, "field3":"country3" } }';

  $Array = json_decode($json, true);

  foreach ($Array as $key => $value) 

  {

       echo " $key ";
       foreach ($value as $k => $val)   
      {
            echo "$k | $val <br />";
       }    
 }

回答by mario

This is not a JSON issue. You just need to traverse the arrays. A simple print_r($json);will show you the structure.

这不是 JSON 问题。你只需要遍历数组。一个简单的print_r($json);将向您展示结构。

In your case you probably need:

在您的情况下,您可能需要:

foreach ($json["items"] as $item) {
    foreach ($item["product"] as $key => $value) {
        echo $key . " : " . $value;
    }
}

The first foreach loops over the item list. And the second subarray access ["product"]will get you to the desired attributes.

第一个 foreach 循环遍历项目列表。第二个子阵列访问["product"]将使您获得所需的属性。