How to get slice of an array where date is the key of array?
I have an array that has date (e.g "2011-10-31") as key and some value associated w开发者_Python百科ith it. The array is sorted. Now, I want to slice the array by giving starting date and ending date? How can I do it in PHP?
Simple loop over it:
function getRange($array, $start, $end) {
$inRange = false;
$result = array();
foreach($array as $date => $value) {
if($date >= $start && !$inRange) {
$inRange = true;
}
if($date > $end) {
break;
}
if($inRange) {
$result[$date] = $value;
}
}
return $result;
}
If start and end date match the keys in the array exactly, you could also use a combination of array_keys
, array_search
and array_slice
(but might not be faster):
function getRange($array, $start, $end) {
$keys = array_keys($array);
$starti = array_search($start, $keys);
$endi = array_search($end, $keys);
return array_slice($array, $starti, $endi-$starti+1);
}
I assumed you want to have the start and end date in the result array.
Of course you have to think about what you should happen if the start and/or end date are not in the array.
精彩评论