Let’s say I have an array that has 4 arrays in it. What I need to do is take the one that has most numbers in it, if I have 2 or more arrays with same max numbers in it I will combine them.
Example array, we see that array 0 and 3 have max members that is 3. So what I will do is take them and combine.
Array
(
[0] => Array
(
[0] => 5
[1] => 6
[2] => 4
)
[1] => Array
(
[0] => 5
[1] => 6
)
[2] => Array
(
[0] => 4
)
[3] => Array
(
[0] => 6
[1] => 6
[2] => 9
)
)
This is what I have, it works but I think it can be done better.
// Getting arrays that have most members in it
$max = count($groupArray[0]);
foreach ($groupArray as $group) {
if (count($group) > $max) {
$max = count($group);
}
}
// Taking all those arrays and combining them in one
$finishArray = array();
foreach ($groupArray as $group) {
if (count($group) == $max) {
foreach ($group as $key) {
array_push($finishArray, $key);
}
}
}
So can it be done better or this is how it should look like?
I think you can do it in one loop instead of two.
Instead of finding the max in one loop and searching for that max in a second loop, search while you are looping, and change the max if you find a bigger array and reset your result. You know there is no match before that point, so you can go on.