Reputation:
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
Reputation: 68536
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.
echo $doge =$obj[0]->last_price;
(or)
echo $doge =$obj[0]->{'last_price'};
Upvotes: 2
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