I have result in array like this
Array
(
[2023-06-09 10:21:48] => Array
(
[count] => 0
)
[2023-06-09 10:21:50] => Array
(
[count] => 1
)
[2023-06-09 10:21:51] => Array
(
[count] => 0
)
[2023-06-09 10:21:52] => Array
(
[count] => 1
)
...
[2023-06-09 10:22:53] => Array
(
[count] => 3
)
...
[2023-06-09 10:23:54] => Array
(
[count] => 1
)
)
But i need to group that result in another foreach and SUM values (count) so result should be
Array
(
[2023-06-09 10:21] => Array
(
[count] => 2
)
[2023-06-09 10:22] => Array
(
[count] => 3
)
[2023-06-09 10:23] => Array
(
[count] => 1
)
)
So basically i need to group result by time and minutes. This is what I need but how to sum values and group tham every minutes ?
foreach ($array as $key => $value) {
$timeFirst = strtotime(date("Y-m-d H:i",strtotime($key)));
$timeSecond = strtotime(date("Y-m-d H:i"));
$final = ($timeSecond - $timeFirst) / 60;
$finalArray[$final.' minutes ago'] = $value;
}
2
Answers
A simple foreach loop and the use of the DateTime builtin class to make the change to the time should do this nicely
And the results
Of course instead of using DateTime to remove the seconds like this
you could simply chop off the las 3 characters of the date and time like this
It’s not clear if you want the result like the section ‘so result should be’ or like the code you posted "$finalArray[$final.’ minutes ago’]
For the first option you can simply strip the seconds:
EDIT
For your request on the past minutes, I suggest you run a further cycle, taking advantage of the fact that the rows to be processed will have decreased:
I haven’t added the ‘minutes ago’ string because it’s ever the same, evaluate yourself if it’s needed.
Another interesting option can be adding a value to the previous array instead of using the $veryFinalArray: