user3395842
user3395842

Reputation:

PHP JSON decoding with one square bracket

Ok so I'm grabing market data with php and it's been working fine but I came across an api that gives me this [{"market_id":"16","code":"DOGE","last_price":"0.00000136","yesterday_price":"0.00000140","exchange":"BTC","change":"-2.86","24hhigh":"0.00000150","24hlow":"0.00000132","24hvol":"6.544"}]

and normally I grab it with this code

$data = curl_exec($c);
curl_close($c);
$obj = json_decode($data);
$doge = print_r($obj->{'last_price'}."\n", true);

but it's not working because of the brackets "[". No other api has these.

How do I get around them to get the information?

Upvotes: 2

Views: 807

Answers (2)

When you do a print_r of your object, you can see the structure like this.

Array
(
    [0] => stdClass Object
        (
            [market_id] => 16
            [code] => DOGE
            [last_price] => 0.00000136
            [yesterday_price] => 0.00000140
            [exchange] => BTC
            [change] => -2.86
            [24hhigh] => 0.00000150
            [24hlow] => 0.00000132
            [24hvol] => 6.544
        )

)

So to access it , you can see the last_price is under the array index 0 , So you need to provide the index before your object.

Accessing ways..

echo $doge =$obj[0]->last_price;

(or)

echo $doge =$obj[0]->{'last_price'};

Demo

Upvotes: 2

Sergey Tsibel
Sergey Tsibel

Reputation: 1625

The response, you are getting is actually an array. First (and the only one in your case) element is an object. Therefore, in order to access this object you would simply call:

$array = json_decode($data);
$obj = $array[0];
$doge = print_r($obj->{'last_price'}."\n", true);

Upvotes: 0

Related Questions