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

Asked

Viewed 635 times

6

have this array

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

And I need the key name of the big three, because in all variables are stored numbers, as I can do ?

2 answers

8


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

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

2 - Then you can use the function array_slice to pick up the first 3 vector elements.

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

Upshot:

arsort($qtd);
$array_ordenado = array_slice($qtd, 0, 3);
$somente_chaves = array_keys($array_ordenado);
  • 1

    +1, explored the language well :)

2

You can do it like 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));

Exit:

/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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.