简体   繁体   English

使用php解析json

[英]Parse json using php

This is my json 这是我的json

{
  "product": [
    {
      "styles": [
        {
          "price": "$65.00"
        },
        {
          "price": "$65.00"
        }
      ],
      "productId": "444",

    }
  ],
  "statusCode": "200"
}

I am trying to get the all the price.. I tried the below code but couldn't get the results 我正在尝试获取所有价格。.我尝试了以下代码,但无法获得结果

$obj = json_decode($response);
foreach($obj['product']['styles'] as $chunk) {
echo $chunk['price'];
}

If you want to access decoded data as an associative array, you should pass true as the second parameter of the json_decode() function: 如果要将解码的数据作为关联数组访问,则应将true作为json_decode()函数的第二个参数传递:

foreach($obj['product'] as $products) {
    foreach ($products['styles'] as $style) {
        echo $style['price'];
    }
}

You've got nested arrays. 您已经嵌套了数组。 product contains an array objects, so you'd actually need 产品包含一个数组对象,因此您实际上需要

$obj = json_decode($response);
echo $obj->product[0]->productID; // 44
                  ^^^---
echo $obj->product[0]->styles[1]->price; // second $65.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM