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!
5
Answers
The answer is already in my question. The provided code does work if I loop through a nice array. I hope I did not make the array fit the solution ;-)
Anyway. This is how you can reproduce it!
RESULT
UPDATE TO RESULT
Turns out Answer #1 is not correct and the array was indeed made to fit the solution.
If you test with
the result will be
Question is, what is missing? :-)
Since you are using mysql, it might be good idea to leave the dirty work to database and use GROUP BY function on status column and then retrieve the result array.
You can find example for this on this page
PHP & MYSQL: using group by for categories
Here’s the algo for your use case. Should work on any other use case:
RESULT
Output:
Short explanation:
array_reduce
starts with this initial result array:And it starts also with this input array:
The result of it looks like this:
The last step is to apply
max
to each color item in the result array withinarray_map
.I have tested both arrays which you have shared i.e.
AND
And my code works as expected.
Here is my code: