Reputation: 59
I have an array like this:
Array
(
[0] => Array
(
[date] => 1523752578
[weight1] => 1890
[weight2] => 1760
)
[1] => Array
(
[date] => 1523756192
[weight1] => 1890
[weight2] => 1760
)
[2] => Array
(
[date] => 1523759807
[weight1] => 1890
[weight2] => 1760
)
[3] => Array
(
[date] => 1523763423
[weight1] => 1890
[weight2] => 1760
)
)
How can I get an array from the array, between two [date] values?
An example, the first value is 1523756192
and the second value is 1523763423
, that should return an array containing [1]
, [2]
and [3]
but not [0]
, and the array should still contain [weight1]
and [weight2]
The "to" and "from" value would come from two inputs, where a user selects two dates. Then I would select all the child arrays from the parent array that is between the two dates.
Upvotes: 1
Views: 60
Reputation: 1357
I think you are looking for array_filter.
function filterbydate($arr, $lowdate, $highdate) {
return array_filter($arr, function($val) use ($lowdate, $highdate) {
return $val['date'] >= $lowdate && $val['date'] <= $highdate;
});
}
// your data
$arr = [['date' => 1523752578,
'weight1' => 1890,
'weight2' => 1760],
['date' => 1523756192,
'weight1' => 1890,
'weight2' => 1760],
['date' => 1523759807,
'weight1' => 1890,
'weight2' => 1760],
['date' => 1523763423,
'weight1' => 1890,
'weight2' => 1760]];
var_dump(filterbydate($arr, 1523756192, 1523763423));
Please note, this retains index values, so the results will have indices of 1, 2, and 3. If you want them renumbered, you can use array_values on the resultant array - so replace the filterbydate internals with:
return array_values(
array_filter($arr, function($val) use ($lowdate, $highdate) {
return $val['date'] >= $lowdate && $val['date'] <= $highdate;
}));
Upvotes: 1