Brian V.
Brian V.

Reputation: 37

nested array with json

$url2 = "http://www.website.com/test.json";
$json2 = file_get_contents($url2);
$data2 = json_decode($json2);

foreach($data2 as $mydata2) {

    $product_discount = $mydata2->applied_discounts;
    var_dump($product_discount);
}

This is returning:

array(1) {
    [0]=> object(stdClass)#2 (2) {
        ["id"]=> string(6) "coupon"
        ["amount"]=> float(9.99)
    }
}

I want to return just the amount of "9.99"

I tried $product_discount[0]['amount'], but that doesn't seem to be right??

Upvotes: 0

Views: 62

Answers (3)

Gavin
Gavin

Reputation: 2143

It's an object, not an array. Try...

$product_discount[0]->amount

Upvotes: 0

matewka
matewka

Reputation: 10148

You want to do this:

$product_discount = $mydata2->applied_discounts[0]->amount;

Upvotes: 3

Amal Murali
Amal Murali

Reputation: 76656

It's an object, so you need the following syntax:

$product_discount = $mydata2->applied_discounts[0]->amount;

However, if you want an array instead, you could set json_decode()'s second parameter as TRUE:

$data2 = json_decode($json2, TRUE);

Upvotes: 6

Related Questions