1

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

1
  • Can you share what you have tried and the issues that you had with that? Commented Dec 15, 2015 at 20:55

2 Answers 2

5
array_count_values( array_map(function($v) { return $v->userId; }, $array) );

result

Array
(
    [3] => 1
    [2] => 2
)
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm. Thank you very much :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.