我尝试使用PHP curl连接Coinmarketcap的API,以从中获取实时比特币价格。关键是它提供的输出太混乱了,以至于我不知道如何从中取出“价格”。周围也有类似的问题,但不幸的是,这些答复对我没有帮助。所以我想知道如何从API给出的回报中去除比特币的价格?由于我仍然是新手,因此似乎在误解数组和对象。 这是“ die and dump”返回的内容:
#data: array:1 [▼
"response" => """
{
"status": {
"timestamp": "2019-04-15T14:03:35.573Z",
"error_code": 0,
"error_message": null,
"elapsed": 5,
"credit_count": 1
},
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"circulating_supply": 17646787,
"total_supply": 17646787,
"max_supply": 21000000,
"date_added": "2013-04-28T00:00:00.000Z",
"num_market_pairs": 7253,
"tags": [
"mineable"
],
"platform": null,
"cmc_rank": 1,
"last_updated": "2019-04-15T14:02:29.000Z",
"quote": {
"USD": {
"price": 5166.87433557,
"volume_24h": 11238888046.6075,
"percent_change_1h": 0.0140845,
"percent_change_24h": 1.39641,
"percent_change_7d": -0.981349,
"market_cap": 91178730855.57031,
"last_updated": "2019-04-15T14:02:29.000Z"
}
}
}
]
}
"""
]
以下是从API请求的代码:
function apiGet($url)
{
$parameters = [
'start' => '1',
'limit' => '3',
];
$query = http_build_query($parameters);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "$url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 30000,
CURLOPT_POST => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept-Encoding: deflate, gzip',
'X-CMC_PRO_API_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
),
)
);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
print_r(json_decode($response));
}
return view('price', compact('response'));
}
$parameters = [
'start' => '1',
'limit' => '1',
];
$query = http_build_query($parameters);
$btc = new \App\Http\Controllers\CoinsController();
$result = $btc->apiGet('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'."?".$query);
dd($result);
答案 0 :(得分:1)
那是一个嵌套的键值数组,其中包含一个json字符串。您可以这样获得价格:
$price = json_decode($result['response'])->data[0]->quote->USD->price;
答案 1 :(得分:1)
据您所知。您可以使用Laravel提供的Arr::get()
帮助程序。参见docs:
use \Illuminate\Support\Arr;
...
$data = json_decode($result['response'], true);
$price = Arr::get($data, 'data.0.quote.USD.price');