aaaaaa
aaaaaa

Reputation: 2618

array_count_values() with objects as values

I was wondering, is there something similar to array_count_values, but that works with objects ?

Let me explain:

array_count_values takes an array as argument, such as

[1]

Array (
    [0] => banana
    [1] => trololol
)

If i give that array to array_count_values, i will get something like:

[2]

Array (
    [banana] => 1
    [trololol] => 1
)

Now lets say that instead of strings, i have objects, that i want to count based on one of their properties. So i have:

[3]

Array (
    [0] => stdClass Object (
        [name] => banana
        [description] => banana, me gusta!
    )
    [1] => stdClass Object (
        [name] => trololol
        [description] => trolololololol
    )
)

And i'd want the magical-function-im-looking-for to count the number of objects with the same name property, returning the same input as [2]

Obviously i could easily do that on my own, but i was just wondering if there was a built-in function for that, since i couldnt seem to find one. Thanks, kind SOers!

Upvotes: 1

Views: 3445

Answers (3)

Don't Panic
Don't Panic

Reputation: 41810

Since PHP 7.0, you can use array_column for this.

$counts = array_count_values(array_column($array_of_objects, 'name'));

When this question was originally asked and answered array_column didn't exist yet. It was introduced in PHP 5.5, but it couldn't handle arrays of objects until 7.0.

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 77976

Check out the Reflection classes to easily fetch information about your objects dynamically.

Upvotes: 0

hakre
hakre

Reputation: 197775

No such function exists. You always need to first map the values you would like to count (and those values must be string or integer):

$map = function($v) {return $v->name;};

$count = array_count_values(array_map($map, $data));

Upvotes: 5

Related Questions