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'];
}
asked Feb 9, 2014 at 18:29
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'];
 }
}
answered Feb 9, 2014 at 18:31
3
  • I get Undefined index: styles and Invalid argument supplied for foreach(). Commented Feb 9, 2014 at 18:33
  • This answer is correct - but also the supplied JSON isn't valid. The comma after "productId": "444" should be removed Commented Feb 9, 2014 at 18:35
  • @Naren I've updated the answer to match exectly your json schema. Commented Feb 9, 2014 at 18:42
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
answered Feb 9, 2014 at 18:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.