There is a large array with timestamps, e.g.:
$timestamps = array();
for ($i = 0; $i < 5000; $i ) {
$timestamps[] = mt_rand(strtotime('1900-01-01 00:00:00 am'), strtotime('2100-12-31 11:59:59 pm'));
}
Now I need to return the timestamps with the earliest (min) and latest (max) clock time.
My approach:
echo date('Y-m-d h:i:s a', min(array_map('callback', $timestamps)));
echo "\n";
echo date('Y-m-d h:i:s a', max(array_map('callback', $timestamps)));
function callback($timestamp) {
return strtotime(date('h:i:s a', $timestamp));
}
This actually provides the earliest and latest clock time, but of course along with the current date (today).
How to return the original timestamps with the earliest and latest clock time?
CodePudding user response:
You can use next code:
//run array_reduce over array
$res = array_reduce(
$timestamps, // timestaps array
function($res, $t) {
// get time from timestamp
$time = date('H:i:s', $t);
// if result min not exists
// or more then $time store new value to $res['min']
if (is_null($res['min'][0]) || $time<$res['min'][0])
$res['min'] = [$time, date('Y-m-d h:i:s a', $t)];
// if result max not exists
// or less then $time store new value to $res['max']
if (is_null($res['max'][0]) || $time>$res['max'][0])
$res['max'] = [$time, date('Y-m-d h:i:s a', $t)];
// return updated result
return $res;
},
// define initial $res with null values
['min'=>[null, null], 'max'=>[null, null]]
);
Result:
Array
(
[min] => Array
(
[0] => 00:00:30
[1] => 1997-05-03 12:00:30 am
)
[max] => Array
(
[0] => 23:59:36
[1] => 1983-07-21 11:59:36 pm
)
)