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
array_count_values( array_map(function($v) { return $v->userId; }, $array) );
result
Array
(
[3] => 1
[2] => 2
)
You could keep the count in the User object. Every time you add a car, increment the count for the appropriate user. Every time you remove a car, decrement the count. This will be faster, but more error prone - if you forget to increment or decrement the count at some point, your data will be wrong.