解析JSON时出现问题(无法使用Foreach循环)

时间:2019-05-24 14:16:58

标签: php json

我正在尝试解析JSON文件,但是有问题。我无法在foreach循环中成功解析它。但是,我可以按以下方式正常解析它:

工作代码:

<?php
$file = file_get_contents('datas.json');
$obj= json_decode($file,true);

echo $obj['getstorebylabel.coupons.0']['code'];
?>

JSON文件:

{
   "getstorebylabel":{
      "storeId":"1",
      "avgSavings30d":913,
      "country":"US",
      "coupons":[
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.0",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.1",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.2",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.3",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.4",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.5",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.6",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.7",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.8",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.9",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.10",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.11",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.12",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.13",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.14",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.15",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.16",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.17",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.18",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.19",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.20",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.21",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.22",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.23",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.24",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.25",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.coupons.26",
            "typename":"StoreDeal"
         }
      ],
      "hasIcon":true,
      "indexShopPage":true,
      "label":"amazon",
      "name":"Amazon",
      "numSavings24h":8,
      "position":null,
      "sales":[
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sales.0",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sales.1",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sales.2",
            "typename":"StoreDeal"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sales.3",
            "typename":"StoreDeal"
         }
      ],
      "sections":[
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sections.0",
            "typename":"StoreSection"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sections.1",
            "typename":"StoreSection"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sections.2",
            "typename":"StoreSection"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sections.3",
            "typename":"StoreSection"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sections.4",
            "typename":"StoreSection"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sections.5",
            "typename":"StoreSection"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sections.6",
            "typename":"StoreSection"
         },
         {
            "type":"id",
            "generated":true,
            "id":"getstorebylabel.sections.7",
            "typename":"StoreSection"
         }
      ],
      "supported":true,
      "url":"https://www.amazon.com",
      "gold":null,
      "isUGCEnabled":true,
      "__typename":"Store"
   },
   "getstorebylabel.coupons.0":{
      "dealId":"211304289714646296",
      "appliedCount":168,
      "appliedLastDiscount":357,
      "appliedLastTs":1558662612714,
      "code":"MHSURVEY",
      "type":"COUPON",
      "rank":0.512,
      "exclusive":false,
      "url":null,
      "created":1554782322737,
      "description":"30% off Maple Holistics Products",
      "hidden":false,
      "meta":{
         "type":"id",
         "generated":true,
         "id":"getstorebylabel.coupons.0.meta",
         "typename":"StoreDealMeta"
      },
      "__typename":"StoreDeal"
   },
   "getstorebylabel.coupons.0.meta":{
      "couponClass":"Popular coupon",
      "percentOff":"30%",
      "dollarOff":null,
      "dollarMinimum":null,
      "noMinimum":null,
      "freeShipping":null,
      "freeDelivery":null,
      "limitedTime":null,
      "firstPurchase":null,
      "entirePurchase":null,
      "anyItem":null,
      "sitewide":null,
      "freeGift":null,
      "bogo":null,
      "onlineOnly":null,
      "exclusions":null,
      "__typename":"StoreDealMeta"
   },
   "getstorebylabel.coupons.1":{
      "dealId":"219054111189457143",
      "appliedCount":4,
      "appliedLastDiscount":2888,
      "appliedLastTs":1558568501177,
      "code":"IMTF9PRM",
      "type":"COUPON",
      "rank":0.525,
      "exclusive":false,
      "url":null,
      "created":1558566415196,
      "description":"",
      "hidden":false,
      "meta":{
         "type":"id",
         "generated":true,
         "id":"getstorebylabel.coupons.1.meta",
         "typename":"StoreDealMeta"
      },
      "__typename":"StoreDeal"
   },
   "getstorebylabel.coupons.1.meta":{
      "couponClass":"Verified coupon",
      "percentOff":null,
      "dollarOff":null,
      "dollarMinimum":null,
      "noMinimum":null,
      "freeShipping":null,
      "freeDelivery":null,
      "limitedTime":null,
      "firstPurchase":null,
      "entirePurchase":null,
      "anyItem":null,
      "sitewide":null,
      "freeGift":null,
      "bogo":null,
      "onlineOnly":null,
      "exclusions":null,
      "__typename":"StoreDealMeta"
   },
   "getstorebylabel.coupons.2":{
      "dealId":"219079319201149290",
      "appliedCount":3,
      "appliedLastDiscount":1698,
      "appliedLastTs":1558659207176,
      "code":"68GIWR5O",
      "type":"COUPON",
      "rank":0.688,
      "exclusive":false,
      "url":null,
      "created":1558578723277,
      "description":"68% off Spaire Lady Electric Shaver Bikini Trimmer. End Date: 05/31/2019.",
      "hidden":false,
      "meta":{
         "type":"id",
         "generated":true,
         "id":"getstorebylabel.coupons.2.meta",
         "typename":"StoreDealMeta"
      },
      "__typename":"StoreDeal"
   },
   "getstorebylabel.coupons.2.meta":{
      "couponClass":"Verified coupon",
      "percentOff":"68%",
      "dollarOff":null,
      "dollarMinimum":null,
      "noMinimum":null,
      "freeShipping":null,
      "freeDelivery":null,
      "limitedTime":null,
      "firstPurchase":null,
      "entirePurchase":null,
      "anyItem":null,
      "sitewide":null,
      "freeGift":null,
      "bogo":null,
      "onlineOnly":null,
      "exclusions":null,
      "__typename":"StoreDealMeta"
   },
   "getstorebylabel.sales.0":{
      "dealId":"211953319159300816",
      "appliedCount":0,
      "appliedLastDiscount":0,
      "appliedLastTs":0,
      "code":"29652f8f0903a8bc011180586e7ca4d1",
      "type":"SALE",
      "rank":0,
      "exclusive":false,
      "url":null,
      "created":1555099231272,
      "description":"Deal of the Day: Samsung 27\" Curved Monitor (Certified Refurbished) Was: #199.99 Now: #149.99.",
      "meta":{
         "type":"id",
         "generated":true,
         "id":"getstorebylabel.sales.0.meta",
         "typename":"StoreDealMeta"
      },
      "__typename":"StoreDeal"
   },
   "getstorebylabel.sales.0.meta":{
      "couponClass":null,
      "percentOff":null,
      "dollarOff":null,
      "dollarMinimum":null,
      "noMinimum":null,
      "freeShipping":null,
      "freeDelivery":null,
      "limitedTime":null,
      "firstPurchase":null,
      "entirePurchase":null,
      "anyItem":null,
      "sitewide":null,
      "freeGift":null,
      "bogo":null,
      "onlineOnly":null,
      "exclusions":null,
      "__typename":"StoreDealMeta"
   },
   "getstorebylabel.sales.1":{
      "dealId":"168100567928401995",
      "appliedCount":0,
      "appliedLastDiscount":0,
      "appliedLastTs":0,
      "code":"59770a2f07c3475eea47d7f024b7eebe",
      "type":"SALE",
      "rank":0,
      "exclusive":false,
      "url":null,
      "created":1533686775897,
      "description":"15-20% off Bakery On Main.",
      "meta":{
         "type":"id",
         "generated":true,
         "id":"getstorebylabel.sales.1.meta",
         "typename":"StoreDealMeta"
      },
      "__typename":"StoreDeal"
   },
   "getstorebylabel.sales.1.meta":{
      "couponClass":null,
      "percentOff":"15-20%",
      "dollarOff":null,
      "dollarMinimum":null,
      "noMinimum":null,
      "freeShipping":null,
      "freeDelivery":null,
      "limitedTime":null,
      "firstPurchase":null,
      "entirePurchase":null,
      "anyItem":null,
      "sitewide":null,
      "freeGift":null,
      "bogo":null,
      "onlineOnly":null,
      "exclusions":null,
      "__typename":"StoreDealMeta"
   },
   "getstorebylabel.sales.2":{
      "dealId":"200238048819388825",
      "appliedCount":0,
      "appliedLastDiscount":0,
      "appliedLastTs":0,
      "code":"7eadc106efd5b822bbf29cf5794070c7",
      "type":"SALE",
      "rank":0,
      "exclusive":false,
      "url":null,
      "created":1549378884253,
      "description":"Exclusive Outlet Special Offers.",
      "meta":{
         "type":"id",
         "generated":true,
         "id":"getstorebylabel.sales.2.meta",
         "typename":"StoreDealMeta"
      },
      "__typename":"StoreDeal"
   },
   "getstorebylabel.sales.2.meta":{
      "couponClass":null,
      "percentOff":null,
      "dollarOff":null,
      "dollarMinimum":null,
      "noMinimum":null,
      "freeShipping":null,
      "freeDelivery":null,
      "limitedTime":null,
      "firstPurchase":null,
      "entirePurchase":null,
      "anyItem":null,
      "sitewide":null,
      "freeGift":null,
      "bogo":null,
      "onlineOnly":null,
      "exclusions":null,
      "__typename":"StoreDealMeta"
   },
   "getstorebylabel.sales.3":{
      "dealId":"168100600865268070",
      "appliedCount":0,
      "appliedLastDiscount":0,
      "appliedLastTs":0,
      "code":"e1f845a00d73ba812daa307fa249be99",
      "type":"SALE",
      "rank":0,
      "exclusive":false,
      "url":null,
      "created":1533686789807,
      "description":"20% off Nescafe.",
      "meta":{
         "type":"id",
         "generated":true,
         "id":"getstorebylabel.sales.3.meta",
         "typename":"StoreDealMeta"
      },
      "__typename":"StoreDeal"
   },
   "getstorebylabel.sales.3.meta":{
      "couponClass":null,
      "percentOff":"20%",
      "dollarOff":null,
      "dollarMinimum":null,
      "noMinimum":null,
      "freeShipping":null,
      "freeDelivery":null,
      "limitedTime":null,
      "firstPurchase":null,
      "entirePurchase":null,
      "anyItem":null,
      "sitewide":null,
      "freeGift":null,
      "bogo":null,
      "onlineOnly":null,
      "exclusions":null,
      "__typename":"StoreDealMeta"
   },
   "getstorebylabel.sections.0":{
      "sectionId":"209004836065609595",
      "sectionType":"about",
      "sectionHeader":"About Amazon",
      "sectionBody":"With Amazon, you can shop online from the world’s largest selection of books, clothing, furniture, movies, music and games, electronics, computers, toys, and more featuring all of your favorite brands. Amazon has the biggest variety and the lowest prices on nearly anything you would shop online for. Customers enjoy the convenience of Amazon’s one stop shopping experience, and the fast and easy shipping from Amazon Prime. If you have an Amazon Alexa, you can use voice commands to have Alexa search, review, and confirm your order for you. Alexa will read product names, prices and even estimate delivery times. Alexa also uses your order history to help you restock the exact items you know you love.",
      "__typename":"StoreSection"
   },
   "getstorebylabel.sections.1":{
      "sectionId":"209004836301765531",
      "sectionType":"section",
      "sectionHeader":"Return Policy",
      "sectionBody":"In most cases, items shipped from Amazon.com are eligible to be returned within 30 days of the confirmation of shipment.  In some cases, individual products have unique policies associated with them. Amazon will automatically reimburse up to #20 for return shipping costs associated with any eligible item. If your return shipping costs more than #20, contact Amazon Customer Service to request a refund of the full shipping cost. If you receive and then return a defective, damaged or incorrect item, Amazon will refund the entire shipping cost, as soon as your return is processed.",
      "__typename":"StoreSection"
   },
   "getstorebylabel.sections.2":{
      "sectionId":"209004836406718538",
      "sectionType":"section",
      "sectionHeader":"Free Shipping Policy",
      "sectionBody":"All orders of at least #25 of any combination eligible items qualify for free standard shipping. In some cases, there are additional specific options or requirements for free shipping, which will always be shown at checkout. With Amazon Prime, users enjoy unlimited free 2-day shipping on orders consisting of any combination of eligible items. Certain items are even eligible for free 1-day shipping for Amazon Prime members.",
      "__typename":"StoreSection"
   },
   "getstorebylabel.sections.3":{
      "sectionId":"209005103444921313",
      "sectionType":"tip",
      "sectionHeader":"Subscribe and Save",
      "sectionBody":"Set up repeating scheduled deliveries through Amazon to unlock savings and save time ordering your favorite products. When you subscribe more, you save more - save up to 15% off on regularly scheduled orders with at least 5 products.",
      "__typename":"StoreSection"
   },
   "getstorebylabel.sections.4":{
      "sectionId":"209005104105164817",
      "sectionType":"tip",
      "sectionHeader":"View Price History",
      "sectionBody":"Check the item’s Price History, courtesy of Honey, to see how much the price has fallen in the past to get a better idea if now is the best time to buy.",
      "__typename":"StoreSection"
   },
   "getstorebylabel.sections.5":{
      "sectionId":"209005104461893499",
      "sectionType":"tip",
      "sectionHeader":"Droplist items for later",
      "sectionBody":"Add any item to your Honey Droplist, and Honey will notify you when the price changes.  Keep track items with Droplist and buy them at the lowest price!",
      "__typename":"StoreSection"
   },
   "getstorebylabel.sections.6":{
      "sectionId":"209005104788703598",
      "sectionType":"tip",
      "sectionHeader":"Try Prime",
      "sectionBody":"Sign up for Amazon Prime to enjoy free, easy, fast 2-day shipping on thousands of eligible products across all categories. Save time and money checking out fast with Amazon Prime.",
      "__typename":"StoreSection"
   },
   "getstorebylabel.sections.7":{
      "sectionId":"212495874509891470",
      "sectionType":"section",
      "sectionHeader":"What is a promotional code for Amazon?",
      "sectionBody":"Any vendor can create an Amazon promo code to discount their product on amazon.com. There is also an Amazon coupon portal that lists the top Amazon promo codes, coupons, and promotions. To activate these coupons, any user can click \"clip coupon\" for the desired item and the advertised discount will be applied at checkout. You can browse this coupon portal at https://www.amazon.com/Coupons/",
      "__typename":"StoreSection"
   },
   "ROOT_QUERY":{
      "getStoreByLabel({\"label\":\"amazon\"})":{
         "type":"id",
         "generated":true,
         "id":"getstorebylabel",
         "typename":"Store"
      },
      "getOtherStores({\"label\":\"amazon\"})":{
         "type":"json",
         "json":[
            {
               "name":"Bata IN",
               "label":"bata-in",
               "__typename":"Store"
            },
            {
               "name":"Ylang 23",
               "label":"ylang-23",
               "__typename":"Store"
            },
            {
               "name":"The Perfume Spot",
               "label":"the-perfume-spot",
               "__typename":"Store"
            },
            {
               "name":"Yankee Candle",
               "label":"yankeecandle",
               "__typename":"Store"
            },
            {
               "name":"Clinique Australia",
               "label":"clinique-australia-au",
               "__typename":"Store"
            },
            {
               "name":"Harbor Freight Tools",
               "label":"harbor-freight-tools",
               "__typename":"Store"
            },
            {
               "name":"Lights Online",
               "label":"lights-online",
               "__typename":"Store"
            },
            {
               "name":"Wholesale It Online",
               "label":"wholesaleitonline",
               "__typename":"Store"
            },
            {
               "name":"Scrubs & Beyond",
               "label":"scrubsandbeyond",
               "__typename":"Store"
            },
            {
               "name":"Magazines.com",
               "label":"magazines",
               "__typename":"Store"
            }
         ]
      }
   }
}

问题: 我想从JSON数据中获取所有代码描述。我们可以在foreach中做到这一点,但是如果对象标题或名称或其名称每次都不相同怎么办? 正如您在JSON中清楚看到的那样:

getstorebylabel.coupons.0
getstorebylabel.coupons.1
getstorebylabel.coupons.2

每个对象都有不同的标题,但已序列化。我如何运行foreach一次性获得所有数据! 谢谢!

1 个答案:

答案 0 :(得分:0)

使用array_keys获取密钥,然后查看密钥以确定所需的密钥。 此示例使用“ coupon”一词过滤键,但是您可以使用任何需要的过滤。

$obj = json_decode($json, true);

print_r(array_keys($obj));
echo "\n";

foreach(array_keys($obj) as $row) {
    if ( preg_match('/.*coupons.*/', $row)) {
        if ( array_key_exists('code', $obj[$row]) ) {
            echo "Key: {$row}\n";
            echo "Code: {$obj[$row]['code']}\n";
            echo "Description: {$obj[$row]['description']}\n";
        }
    }
}

输出:

Key: getstorebylabel.coupons.0
Code: MHSURVEY
Description: 30% off Maple Holistics Products
Key: getstorebylabel.coupons.1
Code: IMTF9PRM
Description:
Key: getstorebylabel.coupons.2
Code: 68GIWR5O
Description: 68% off Spaire Lady Electric Shaver Bikini Trimmer. End Date: 05/31/2019.