Reputation: 397
I have a JSON of all bitcoin prices for previous 90 days. I'm trying to only work with the weekday prices, excluding weekend prices. This is how I am doing it. Could you please tell me what I'm doing wrong or point me in the right direction?
<?php
$string = file_get_contents("https://blockchain.info/charts/market-price?timespan=90days&format=json");
$btc_price = json_decode($string, true);
$allDays = $btc_price[values];
$weekends = array_filter($allDays[values][x], function($d) {
return (date('N', strtotime(date("Y-m-$d"))) >= 6);
});
$allDays[$year][$month] = array_diff($allDays[$year][$month], $weekends);
echo "<pre>";
print_r($allDays);
?>
Upvotes: 2
Views: 46
Reputation: 7409
You're fairly close. I've made a few changes to get it working:
Instead of passing in $allDays['values']['x']
, you should pass in all of the days. This will allow you to remove each weekend day without having to do the array_diff
step. $allDays['values']['x']
should be $allDays
.
Your expression in the array_filter
callable was wrong. I'm not clear what your intention was, but it looks like you were attempting to get the day of the week and filter on that. That's a good strategy, but your implementation wasn't effective. You can get the day of the week with w
in date and pass in the unix timestamp you were given from the API. Also, checking for greater than 6 wasn't effective, since Sunday is 0.
$weekends = array_filter($allDays[values][x], function($d) { return (date('N', strtotime(date("Y-m-$d"))) >= 6); });
should be changed to:
$allDays = array_filter($allDays, function($d) {
return !(date('w', $d['x']) == 6 || date('w', $d['x']) == 0);
});
$allDays[values][x]
should have been $allDays['values']['x']
.Here's the full snippet so you have context:
<?php
$string = file_get_contents("https://blockchain.info/charts/market-price?timespan=90days&format=json");
$btc_price = json_decode($string, true);
$allDays = $btc_price['values'];
$allDays = array_filter($allDays, function($d) {
return !(date('w', $d['x']) == 6 || date('w', $d['x']) == 0);
});
// This is just done to reset the keys in the array. It's entirely optional.
$allDays = array_values($allDays);
echo "<pre>";
print_r($allDays);
?>
Upvotes: 2