NEO
NEO

Reputation: 2001

Parse json using php

This is my 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'];
}

Upvotes: 0

Views: 39

Answers (2)

ozahorulia
ozahorulia

Reputation: 10084

If you want to access decoded data as an associative array, you should pass true as the second parameter of the json_decode() function:

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

Upvotes: 3

Marc B
Marc B

Reputation: 360562

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

Upvotes: 1

Related Questions