In PHP, it is very common to process arrays, where array_count_values() and asort() are two very useful functions. The array_count_values() function can count the frequency of each element in an array, while the asort() function can sort ascendingly according to the value of the array. This article will introduce how to use these two functions in combination to arrange the array in ascending order according to the frequency of the elements.
First, we need an array and then use the array_count_values() function to count the number of occurrences of each element. array_count_values() returns an associative array where the key is the element in the array and the value is the number of times the element appears.
<?php
$array = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple'];
$frequency = array_count_values($array);
print_r($frequency);
?>
Output:
Array
(
[apple] => 3
[banana] => 2
[orange] => 1
)
In the example above, we can see that apple appears 3 times, banana appears 2 times, and orange appears 1 time.
Next, we can use the asort() function to sort the array_count_values() results. The asort() function sorts the array ascending order based on the values in the array, but keeps the key value associated.
<?php
$array = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple'];
$frequency = array_count_values($array);
// Arrange in ascending order of frequency
asort($frequency);
print_r($frequency);
?>
Output:
Array
(
[orange] => 1
[banana] => 2
[apple] => 3
)
As shown above, asort() sorts the array from low to high according to frequency.
By combining array_count_values() and asort() , we can sort very easily according to the frequency of the elements in the array. array_count_values() is used to count frequency, while asort() is responsible for sorting the frequency ascending order. You can use these functions to process and analyze data, especially in scenarios where you need to be sorted by frequency.
asort() is sorted by value, if you want to sort by key, you can use ksort() .
If the array contains multiple elements of the same frequency, asort() will sort them according to the order in the original array.
The above is the basic method of how to use asort() and array_count_values() to sort arrays by frequency ascending order. If you need to count the frequency and sort it during development, remember to refer to the sample code in this article.