Grouping, assigning and sorting values of a multidimensional array in PHP

0

Hello everyone. I have the following multidimensional array in PHP:

Array ( 
[0] => Array ( [0] => teste0 [1] => 1 ) 
[1] => Array ( [0] => teste1 [1] => 1 ) 
[2] => Array ( [0] => teste2 [1] => 2 ) 
[3] => Array ( [0] => teste3 [1] => 2 )
[4] => Array ( [0] => teste4 [1] => 2 )
[5] => Array ( [0] => teste5 [1] => 3 )
[6] => Array ( [0] => teste6 [1] => 4 )
[7] => Array ( [0] => teste7 [1] => 4 )
)

I would like to rank this array according to the number of equal values that are in the [1] (numeric) value. This would produce the following result:

Array ( 
[0] => Array ( [0] => teste2 [1] => 1 ) 
[1] => Array ( [0] => teste3 [1] => 1 ) 
[2] => Array ( [0] => teste4 [1] => 1 ) 
[3] => Array ( [0] => teste0 [1] => 2 )
[4] => Array ( [0] => teste1 [1] => 2 )
[5] => Array ( [0] => teste6 [1] => 4 )
[6] => Array ( [0] => teste7 [1] => 4 )
[7] => Array ( [0] => teste5 [1] => 3 )
)

How to do this rankings using PHP or Javascript?

    
asked by anonymous 11.06.2018 / 05:32

1 answer

1

The easiest way to solve your problem is to create an array with the counts of each element and then sort it based on the counts.

To create counts, you can create an empty array by adding each element it collects relative to the 1 position of the sub-array:

$contagens = Array();
foreach ($arr as $key => $subArr){
    $val = $subArr[1];
    $contagens[$val] = isset($contagens[$val]) ? $contagens[$val] + 1 : 1;
}

That for the array presented in the question gives the following result:

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

Then you can sort using usort , which allows you to pass a comparison function to the logic that we want. In your case you can compare by the counts, and when the counts are equal, by the actual number itself:

usort($arr, function ($a,$b) use ($contagens){
  return $contagens[$a[1]]==$contagens[$b[1]] ? $a[1]-$b[1]: $contagens[$b[1]]-$contagens[$a[1]];
});

Notice that I had to use use to be able to use the counting array previously found.

After this the final array looks like this:

Array
(
    [0] => Array
        (
            [0] => teste4
            [1] => 2
        )

    [1] => Array
        (
            [0] => teste2
            [1] => 2
        )

    [2] => Array
        (
            [0] => teste3
            [1] => 2
        )

    [3] => Array
        (
            [0] => teste0
            [1] => 1
        )

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

    [5] => Array
        (
            [0] => teste6
            [1] => 4
        )

    [6] => Array
        (
            [0] => teste7
            [1] => 4
        )

    [7] => Array
        (
            [0] => teste5
            [1] => 3
        )

)

See this example on Ideone

    
12.06.2018 / 14:05