简体   繁体   中英

How to take selected value from json response laravel?

I want to get price of btc to usd using coinmarketcap's API.

$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);

Getting 200 Ok response

"data": {
"symbol": "BTC",
"id": "1",
"name": "Bitcoin",
"amount": 50,
"last_updated": "2018-06-06T08:04:36.000Z",
"quote": {
"USD": {
"price": 284656.08465608465,
"last_updated": "2018-06-06T06:00:00.000Z"
},

I want to get Price value from usd but its not working when i tried

$examount = $type->USD->price;

Since you are using

$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);

It means that your object is converted to associative array, to access the price use:

$type['data']['quote']['USD']['price'];

You should be good to go.

Edit In case $type contains more than one element, you will need to loop them.

foreach($type['data'] as $singleQuote){
    $price = $singleQuote['quote']['USD']['price'];
    echo 'Quote for: '.$singleQuote['symbol'].' in USD: '.$price.'<br/>';
}

Because you are passing 2nd param true that will convert it to associative array:

$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);
$examount = $type['data']['quote']['USD']['price'];

I hope above will solve your problem as per the documentation of coinmarketcap ( https://coinmarketcap.com/api/documentation/v1/#section/Endpoint-Overview )

问题是由 $request 返回 null 引起的上述所有内容也是正确的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM