排序数组:倒数第二

时间:2013-01-27 16:06:25

标签: php

ksort ($votes);
        foreach ($votes as $total => $contestant){
        $ordervotes[]= $contestant;
        } 

        echo "<li> And the winner is: {$ordervotes[4]}</li>";
        echo "<li> And the loser is: {$ordervotes[0]}</li>";
        echo "<li> {$ordervotes[1]} came second last</li>";

当'$ total'都不相同时,这样可以正常工作,如果它们是相同的,我会收到错误代码。我意识到我可以使用'max / min'来获取数组的第一个和最后一个元素,但是我如何才能找到最后一个?

谢谢

4 个答案:

答案 0 :(得分:1)

你为什么不试试:

echo $votes[count($votes)-2];

您也不需要使用相同的值填充另一个数组 - 您可以将它们保存在$votes中。您可能还想查看对数组进行排序by value而不是by key(我假设您正在尝试这样做)。


如果您希望重复密钥,则需要重新设置存储数据的方式。考虑使用多维数组:

$votes = array(
   array('name'=>'John','vote'=>10),
   array('name'=>'James','vote'=>11),
   array('name'=>'Jimmy','vote'=>13),
);

您可以使用此函数和代码对此数组进行排序:

// This function will sort your array
function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

// Sort the array by the 'vote' key
aasort($votes,"vote");

// Echo out the name of the second-last person
echo $votes[count($votes)-2]['name'];

答案 1 :(得分:0)

使用此:

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 > $secondMax) {
            $second = $value;
            $secondKey = $key;
        }
    }

    return array($secondKey, $second);
}

用法:

$ second = secondMax($ votes);

答案 2 :(得分:0)

您可以使用函数count来检索它:

$ordervotes[ (count($ordervotes)-2) ]
// the array starts with index 0, so (count($ordervotes)-1) is the last element

答案 3 :(得分:0)

我不明白你的$votes变量中有什么......你怎么能有多个具有相同选票的参赛者(以及使用相同的密钥)。

我认为这里有一个错误。

你的票数应该是这样的:

$votes = array(
    'contestant 1' => 8,
    'contestant 2' => 12,
    'contestant 3' => 3
);

然后订购数组:sort($votes)

最后,获得倒数第二名:$votes[count($votes) - 2];