N1njaWTF N1njaWTF - 1 month ago 5
JSON Question

How to get comma seperated array from JSON response?

Im currently trying to get all the bitcoin prices from the last 30 days in a comma seperated string.

Im getting the price from coinbase api via https://api.coinbase.com/v2/prices/btc-eur/spot?date=11.03.2016 for example.

Now what I did is a for loop where it inserts every date of the last 30 days into the api link and gives me a long string with all prices. I would like to comma seperate each price in that string now.

Here the Code currently:

<?php

for($i=1; $i<=30; $i++)
{
$pricedates = date('Y-m-d', strtotime('-'.$i.' days',strtotime(date('Y-m-d'))));



//Coinbase API for Historical Rates

// Get data from Coinbase API
$url = "https://api.coinbase.com/v2/prices/btc-eur/spot?date=".$pricedates."";
$btcdata = @file_get_contents($url);
$btcdata = json_decode($btcdata, true);

$btcprice = $btcdata['data']['amount'];

}

?>


Would be amazing if someone could help me out! :))

Answer

If you change $btcprice = $btcdata['data']['amount']; into $btcprice[] = $btcdata['data']['amount']; you'll end up with an array with all 30 values.

Then you can use implode() to glue the pieces of the array into a string. $btcprices_str = implode(',', $btcprice);

Comments