php - Parsing a Multi Dimensional JSON string from URL
问题描述
I'm trying to access some values in JSON that are returned form this URL: https://api.crypto-bridge.org/api/v1/ticker
Basically, I want to be able to get last, volume, ask & bid for "id":"FROST_BTC" (for example)
For now, I simply want to echo those out onto a php page.
Like:
Volume = 0.13
Ask = 0.033
Bid = 0.035
Last = 0.034
Due to the amount of data on the page, I'm not sure at all how to go about this ? Any thoughts, examples or readings so I can figure this one out ?
PHP would be preference, but open to try/learn anything.
解决方案
Simply try like this with php curl
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.crypto-bridge.org/api/v1/ticker",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$response_array = json_decode($response,1);
}
/*
# JUST FOR DEBUGGING PURPOSE
print '<pre>';
print_r($response_array);
print '</pre>';
*/
foreach($response_array as $k=>$v){
echo "id = {$v['id']}, last = {$v['last']}, volume = {$v['volume']}, ask = {$v['ask']}, bid = {$v['bid']}";
echo PHP_EOL;
}
?>
EDIT: As per comment
Way 1: use break;
after printing 1st row
foreach($response_array as $k=>$v){
echo "id = {$v['id']}, last = {$v['last']}, volume = {$v['volume']}, ask = {$v['ask']}, bid = {$v['bid']}";
echo PHP_EOL;
break;
}
Way 2 grab first row and then use loop to print it
$first_row = $response_array[0];
foreach($first_row as $k=>$v){
echo "$k = $v";
}
Way 3 using array_filter() for specific row printing
$vacek_required = array_filter($response_array, function ($var) {
return ($var['id'] == 'WGR_BTC');
});
foreach($vacek_required as $k=>$v){
echo "$k = $v";
}