3

我想在数组中找到第二高的变量。

例如,如果我有:

$cookies = array(
                "chocolate" => "20",
                "vanilla" => "14",
                "strawberry" => "18",
                "raspberry" => "19",
                "bluebery" => "29"
);

我可以用它max($cookies)来找到最高的变量,即"bluebery" => "29".

但是我如何找到第二高的呢? "chocolate" => "20"

4

9 回答 9

15

对其进行排序并获得第二项是最简单的方法:

arsort($cookies);
$keys = array_keys($cookies);

echo $keys[1]; // chocolate
echo $cookies[$keys[1]]; // 20

如果您想要一种更有效的方法,您也可以手动完成,同时跟踪最高和次高的项目:

function secondMax($arr) {
    $max = $second = 0;
    $maxKey = $secondKey = null;

    foreach($arr as $key => $value) {
        if($value > $max) {
            $second = $max;
            $secondKey = $maxKey;
            $max = $value;
            $maxKey = $key;
        } elseif($value > $second) {
            $second = $value;
            $secondKey = $key;
        }
    }

    return array($secondKey, $second);
}

用法:

$second = secondMax($cookies);
echo "{$second[0]} => {$second[1]}"; // chocolate => 20
于 2012-06-05T13:05:18.477 回答
5

为了好玩,您可以使用max()两次 :)

例如:

  • 复制数组
  • max()
  • 删除最大值
  • max()再次运行

另一种方法是根据值对数组进行排序并获取数组的第二个元素。我很好奇哪个更快。大概是那种。

于 2012-06-05T13:05:06.557 回答
2
arsort($cookies) AND array_shift($cookies) AND list($k, $v) = each($cookies);
echo "$k => $v"; // chocolate => 20
于 2012-06-05T13:09:14.940 回答
1

尝试 :

asort($cookies);
end($cookies);
prev($cookies);
list($key,$value) = each($cookies);

或反转它

arsort($cookies);
reset($cookies);
next($cookies);
list($key,$value) = each($cookies);

**编辑**

我想无论如何我都会分享这个,如果有人偶然发现这个并需要它:

/**
 * Returns the key => value pair with the specific rank.
 * if $rank is 0, falase is returned. If $rank is positive,
 * then the $rank th smallest pair is returned. If $rank
 * is negative, then the $rank th biggest pair is returned.
 * If $rank range is outside the size of the array, false
 * is returned. If a callable function is provided, it will
 * be used to sort the data. If $keySort is true, then the
 * data will be sorted by keys instead (the callback functions
 * will receive the keys to compare instead of values)
 * 
 * @param $data array
 * @param $rank int
 * @param $cmd_function callable (optional)
 * @param $keySort boolean (optional)
 * @return array            the key => value pair or false
 */
function findByRank($data, $rank, $cmd_function = null, $keySort = false) {
    if (($rank == 0) || (abs($rank) > count($data))) {
        return false;
    }
    $sort = ($keySort?'k':'a').'sort';
    if ($cmd_function != null) {
        $sort = 'u'.$sort;
        $sort($data, $cmd_function);
    } else {
        $sort($data);
    }

    if ($rank > 0) {
        reset($data);
        $next = 'next';
    } else {
        end($data);
        $next = 'prev';
        $rank = abs($rank);
    }
    while (--$rank > 0) $next($data);
    return each($data);
}




$cookies = array(
                "chocolate" => "20",
                "vanilla" => "14",
                "strawberry" => "18",
                "raspberry" => "19",
                "bluebery" => "29"
);

header('Content-type:text/plain; charset=utf-8');
var_dump(findByRank($cookies, -10));  // -> false
var_dump(findByRank($cookies, -2));   // -> 'chocolate' key=>value pair
var_dump(findByRank($cookies, -1));   // -> 'blueberry' key=>value pair
var_dump(findByRank($cookies, 0));    // -> false
var_dump(findByRank($cookies, 1));    // -> 'vanilla' key=>value pair
var_dump(findByRank($cookies, 3));    // -> 'raspberry' key=>value pair
于 2012-06-05T13:05:44.980 回答
1
rsort($cookies);
echo $cookies[1];
于 2012-06-05T13:08:30.860 回答
0

对数组进行降序排序并取第二个值。或者,为了保存,取第一个值并遍历数组,直到找到一个较小的值。

于 2012-06-05T13:05:21.517 回答
0

检查这个网址

http://maheshbokkisam.blogspot.in/2013/04/find-nth-highest-value-in-array-without.html

从给定数组中查找第 N 个/第 N 个最大值,而不使用 PHP 中的任何排序

$ar  =  array(23,56,87,12,98,85,24,54,99,100,1,4,5,2,76,37,92);

$n   = count($ar) - 5;

for($i = 0; $i < $n; $i++){
    // Get the max value from array // get the Nth value from last loop
    echo $a = max($ar); 

    echo "<br /><pre>"; print_r($ar);

    $ar = array_flip($ar);    // Flip the array
    //print_r($ar);

    unset($ar[$a]);           // Unset the max value from array
    //print_r($ar);

    $ar = array_flip($ar);    // Flip the array
    echo "</pre>";
    echo "<hr />";
}

于 2013-04-12T07:51:19.183 回答
0
function second_largest($arr)
{
    sort($arr, SORT_NUMERIC);

    return($arr[count($arr) - 2]);
}

//echo 3

echo second_largest(array(0, 3, 4, 1, 2));
于 2014-06-20T11:50:52.647 回答
0
<?php

 // Finding Second highest number (In case of index of array is random)
$arr = [-5 => 33, -4 => -2, 8 => 0, 44, 44, 44, 44, 44];
$max = -INF;
$secondMax = -INF;
$size = sizeof($arr);
if ($size > 1) {
    foreach ($arr as $key => $value) {
        echo "KEY-> ", $key, "VALUE->", $value, "\n";
        if ($value > $max) {
            $max = $value;
        } else {
            if ($value < $max && $value > $secondMax) {
                $secondMax = $value;
            }
        }
    }
} else if ($size == 0) {
    $max = "No Max element";
    $secondMax = "No Second highest element";
} else {
    foreach ($arr as $key => $value) {
        $max = $arr[$key];
        $secondMax = "No second highest element";
    }
}

echo "maxvalue = ", $max, "\n";
echo "secondmax =", $secondMax;
于 2017-07-31T16:16:31.207 回答