I have an array of cars like this.
Array
(
[2] => Car Object
(
[userId] => 3
[value] => 0
)
[58] => Car Object
(
[userId] => 2
[value] => 0
)
[64] => Car Object
(
[userId] => 2
[value] => 0
)
)
I loop through an array of users and wish to know how many occurrences each userId is represented in the cars array. The array keys are dynamic numbers. Do I need to loop through the cars array each time I loop though the user array? Seems like a lot of looping and I suspect a better solution is available :)
Thanks in advance
Update: I actually just came up with a solution that seems to work. Might not be pretty. Comments are appreciated
$countArray = array();
foreach($cars as $car) {
if(!$countArray[$car->userId()]) $countArray[$car->userId()] == 0;
$countArray[$car->userId()]++;
}
print_r($countArray) gives me
Array ( [94] => 33 [84] => 15 [88] => 53 [80] => 69 [83] => 14 [93] => 3 [76] => 69 [86] => 51 [82] => 77 [87] => 20 [112] => 12 [115] => 16 [114] => 10 [113] => 2 [77] => 1 )
which seems about right