嘗試:
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
選項一:從陣列中刪除最大元素並再次查找最大值。第二:排列數組並取第二個元素。 – Leri
你嘗試過什麼方法?想到一對夫婦的想法:你可以穿過陣列並選出最高的兩個,類似於選擇較高的一個。另一個是你可以挑選第二個。 – GreenMatt