0

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'];
}
0

2 Answers 2

3

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'];
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I get Undefined index: styles and Invalid argument supplied for foreach().
This answer is correct - but also the supplied JSON isn't valid. The comma after "productId": "444" should be removed
@Naren I've updated the answer to match exectly your json schema.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.