Skip to content
Advertisement

More efficient way to sort unique values from array of arrays by occurrences in PHP

What would be the most efficient PHP way to get unique values from an array of arrays and sort them by number of occurrences from most frequent to least?

Example input array:

JavaScript

Would result in this output array:

JavaScript

The alphabetical order of values with same number of occurrences is not important.

So far I’m merging the array of arrays:

JavaScript

Then creating a new array where values become keys. And values are the number of times they occur in the original array of arrays.

JavaScript

Then I can sort by value

JavaScript

And create a new array where keys become values again.

JavaScript

What would be a more efficient way to do that?

Advertisement

Answer

The simplest I can come up with is to start with the array_merge(), but using the splat (...) to merge all of the arrays. Then use the inbuilt array_count_values() to summarize the values and then arsort() to sort them…

JavaScript

This gives the output of…

JavaScript

using

JavaScript

gives…

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement