Reputation: 1702
Straight to the question -
If $n = 3,
and input is -
Array
(
[04] => 3
[07] => 4
[01] => 5
[06] => 5
[05] => 5
[03] => 6
[08] => 6
[02] => 7
[09] => 8
[12] => 9
[10] => 10
[15] => 10
[19] => 11
[20] => 11
[13] => 12
[21] => 12
[16] => 13
[14] => 14
[22] => 14
[23] => 15
[11] => 15
[00] => 15
[17] => 17
[18] => 17
)
Output should be -
Array
( [14] => 14
[22] => 14
[23] => 15
[11] => 15
[00] => 15
[17] => 17
[18] => 17
)
Thank you, all, for help.
Upvotes: 1
Views: 145
Reputation: 26
Really fast, no loop, only built-in PHP function needed
function getMaxValues($array, $number) { $tmp = $array; asort($array); $values_cnt = array_count_values($array); $max_val_cnt = array_slice($values_cnt, count($values_cnt)-$number); $max_val_cnt = array_sum($max_val_cnt); $ret = array_slice($tmp, count($tmp)-$max_val_cnt, $max_val_cnt, true); return $ret; }
Upvotes: 0
Reputation: 86406
arsort($array);
function output($array,$n)
{
$c=0;
$newArray=array();
foreach ($array as $key => $value)
{
if ($c == $n)
{
$newArray[$key]=$value;
return $newArray;
}
if (!in_array($value, $newArray))
{
$c++;
}
$newArray[$key]=$value;
}
}
Upvotes: 1
Reputation: 48304
Something like:
function biggest_n(array $a, $n)
{
$u = array_unique($a);
if (count($u) <= $n) return $a;
rsort($u);
$val = $u[$n - 1];
return array_filter($a, function($e) use($val) { return $e >= $val; });
}
Upvotes: 5
Reputation: 1702
A quick hack into Shakti's function. But, is this reliable?
function getMaxValues( $array, $total ) {
arsort( $array );
$count = 0;
$return = array();
$total++;
foreach ($array as $key => $value) {
if ( !in_array( $value, $return ) )
$count++;
$return[ $key ] = $value;
if ( $count == $total ) {
array_pop($return);
return $return;
}
}
}
Upvotes: 0