Reputation: 15
Basically I have an array that looks like this:
Array
(
Array
(
[action] => call
[when] => today
)
Array
(
[action] => call
[when] => today
)
Array
(
[action] => message
[when] => today
)
Array
(
[action] => facetime
[when] => tomorrow
)
)
What would be the most appropriate way to count the most repeating action and how many times it repeated? Key 'when' does not matter.
Upvotes: 0
Views: 39
Reputation: 807
You might resort to some of the built-in array functions.
Extracting the values of the column 'action'
by using array_column
and passing it to array_count_values
will give us the frequency of each action.
If we then get the maximum number of occurrences by using max
, we can use it to filter the associative array (with array_filter
) to get those that occur most frequent.
$occurrences = array_count_values(array_column($arr, 'action'));
$max = max($occurrences);
return array_filter($occurrences, function ($val) use ($max) {
return $val === $max;
});
Upvotes: 1