php – 如何返回具有最高值的数组元素?

在我的代码中,我有两个元素具有相同的年龄“Joe”=>“43”和“Rob”=>“43”.

我的代码输出是:

Joe

我要输出:

Joe and Rob

因为它们具有最高的价值.

这是我的代码:

<?php
    $cur = 1;

    $age = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
    $new_array = array();
    arsort($age);
    $new_array = $age;
    $key = array_search(max($new_array), $new_array);

    while ($cur > 0) {
        echo $key;
        $cur--;
    }
?>
最佳答案
我将更改数组中的键和值,然后按键排序并返回第一个键的值:

$ages = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
$new = array();

foreach ($ages as $name => $age) {
  $new[$age][] = $name;
}

uksort($new, function($ka, $kb) { return $kb - $ka; }); // or just krsort($new);
$new = array_values($new)[0]; // <- to use this you have to have at least PHP 5.4

// if you have PHP < 5.4 you can simply do it in two steps:
// $new = array_values($new);
// $new = $new[0];

See it in action!

编辑:even simpler!

$ages = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
$max = max($ages);
$new = array_keys(array_filter($ages, function ($age) use ($max) { return $age == $max; }));

转载注明原文:php – 如何返回具有最高值的数组元素? - 代码日志