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
2 Answers 2
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
-
I get Undefined index: styles and Invalid argument supplied for foreach().NEO– NEO2014年02月09日 18:33:48 +00:00Commented 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 removedJamesG– JamesG2014年02月09日 18:35:34 +00:00Commented Feb 9, 2014 at 18:35
-
@Naren I've updated the answer to match exectly your json schema.ozahorulia– ozahorulia2014年02月09日 18:42:06 +00:00Commented Feb 9, 2014 at 18:42
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
lang-php