简体   繁体   English

如何从 json 响应 laravel 中获取选定的值?

[英]How to take selected value from json response laravel?

I want to get price of btc to usd using coinmarketcap's API.我想使用 coinmarketcap 的 API 将 btc 的价格转换为美元。

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

Getting 200 Ok response获得 200 Ok 响应

"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我想从 usd 获取价格值,但是当我尝试时它不起作用

$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.编辑如果$type包含多个元素,您将需要循环它们。

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:因为您正在传递第二个参数true将其转换为关联数组:

$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 )我希望以上内容可以根据 coinmarketcap 的文档( https://coinmarketcap.com/api/documentation/v1/#section/Endpoint-Overview )解决您的问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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