How to know the array key of the 3 biggest results?

6

I have this array

$qtd = array(
'acao' => $acao,
'aventura' => $aventura,
'comedia' => $comedia,
'drama' => $drama,
'faroeste' => $faroeste,
'ficcao' => $ficcao,
'suspense' => $suspense,
'terror' => $terror,
'romance' => $romance);

I need the key name of the 3 major, because in all variables are stored numbers, how can I do?

    
asked by anonymous 08.11.2016 / 17:40

2 answers

8

Pretty simple, you can only use native PHP functions for this.

1 - The function arsort to sort by the highest value, keeping keys in the same state as they were.

2 - Then you can use the array_slice function to get the first 3 elements of the vector.

3 - Finally, use array_keys to list only the keys.

Result :

arsort($qtd);
$array_ordenado = array_slice($qtd, 0, 3);
$somente_chaves = array_keys($array_ordenado);
    
08.11.2016 / 17:51
2

You can do this:

<?php

$qtd = array(
'acao' => 10,
'aventura' => 15,
'comedia' => 20,
'drama' => 15,
'faroeste' => 18,
'ficcao' => 10,
'suspense' => 14,
'terror' => 16,
'romance' => 12);

function maior($array, $quantidade)
{
    $bkp = $array;
    $retorno = array();
    while($quantidade > 0) {
        foreach($bkp as $key => $value) {
            if($value == max($bkp)) {
                $retorno[] = $key;
                $quantidade --;
                unset($bkp[$key]);
                break;
            }
        }
    }
    return $retorno;
}
var_dump($qtd);
var_dump(maior($qtd, 5));

Output:

/home/leonardo/www/maior.php:30:
array (size=9)
  'acao' => int 10
  'aventura' => int 15
  'comedia' => int 20
  'drama' => int 15
  'faroeste' => int 18
  'ficcao' => int 10
  'suspense' => int 14
  'terror' => int 16
  'romance' => int 12

/home/leonardo/www/maior.php:31:
array (size=5)
  0 => string 'comedia' (length=7)
  1 => string 'faroeste' (length=8)
  2 => string 'terror' (length=6)
  3 => string 'aventura' (length=8)
  4 => string 'drama' (length=5)
    
08.11.2016 / 17:53