beingbishwa beingbishwa - 16 days ago 6
PHP Question

Order elements inside this array on the basis of frequency

I am facing this sort of array in the middle of a project. I want it to be sorted on the basis of ID frequency that means which id is repeated most has to come as first element of resulting array. How to do that??

In advance Thanks for help!!!

Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 4
)

[2] => Array
(
[id] => 3
)

[3] => Array
(
[id] => 4
)

[4] => Array
(
[id] => 1
)

[5] => Array
(
[id] => 4
)

[6] => Array
(
[id] => 7
)
)

Answer

If the above array is your structure, then something like this would do the trick for you, to organise the id with it's relevant counts:

$filtered = array_count_values(array_column($myArray, 'id'));
// now sort it: high - low
arsort($filtered);

Which results in the following array:

Array (
    [4] => 3
    [1] => 2
    [3] => 1
    [7] => 1
)

With the above key's being the id column, and the values being the count of times it was present within the initial array

My question to you is; do you need it in it's original format, just ordered, or is a frequency display as above adequate?

Comments