I am fetching data from a mysql database that looks like this:
ID | Status |
---|---|
1 | Green |
2 | Red |
3 | Red |
4 | Green |
5 | Green |
6 | Green |
7 | Green |
8 | Grey |
And I want to find out, what is the highest consecutive count of Red
, Green
and Grey
.
The outcome should be
Green: 4
Red: 2
Grey: 1
I tried How to count the consecutive duplicate values in an array? and Count Number of Consecutive Occurrence of values in Table but this is not exactly what I need.
I dont want to count every occurance and sum it up. I want to know the highest consecutive count of all of them.
I have tried the following, but it only works for certain scenarios.
$consecResult = array();
$prev_value = array("value" => null, "amount" => null);
while($row = $result->fetch_assoc())
{
if ($prev_value['value'] != $row['status'])
{
unset($prev_value);
$prev_value = array('value' => $row['status'], 'amount' => 0);
$consecResult[$row['status']] =& $prev_value;
}
$prev_value['amount']++;
}
Hope that makes sense!
Thanks!