簡體   English   中英

找到數組中第二高的變量

[英]Find the second highest variable in array

我想找到數組中第二高的變量。

例如,如果我有:

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

我可以使用max($cookies)來查找最高變量,即"bluebery" => "29"

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

對它進行排序並獲得第二項是最簡單的方法:

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

為了好玩,你可以使用max()兩次:)

例如:

  • 復制數組
  • 運行max()
  • 刪除最大值
  • 再次運行max()

另一種方法是根據值對數組進行排序,並獲取數組的第二個元素。 我很好奇哪個更快 可能是那種。

arsort($cookies) AND array_shift($cookies) AND list($k, $v) = each($cookies);
echo "$k => $v"; // chocolate => 20

試試:

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
rsort($cookies);
echo $cookies[1];

對數組進行降序排序並獲取第二個值。 或者,要保存,請取第一個值並遍歷數組,直到找到較小的數組。

檢查此URL

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 />"; } 

function second_largest($arr)
{
    sort($arr, SORT_NUMERIC);

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

//echo 3

echo second_largest(array(0, 3, 4, 1, 2));
<?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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM