我有一个数组:
$someArray = array('fb' => 32, 'gp' => 11, 'tw' => 7, 'vk' => 89, 'ok' => 112);
正如您所看到的,数组中的最后一个元素具有最大的价值。我需要返回最后一个元素的键(ok
)。怎么做?
答案 0 :(得分:2)
基于https://stackoverflow.com/a/1461363/1641835:
$someArray = array('fb' => 32, 'gp' => 11, 'tw' => 7, 'vk' => 89, 'ok' => 112);
$max_keys = array_keys($someArray, max($someArray));
// $max_keys would now be an array: [ 'ok' ]
$max_keys
现在将是所有指向最大值的键的数组。如果你知道只有一个,或者你不关心你检索哪个,你可以使用:
$someArray = array('fb' => 32, 'gp' => 11, 'tw' => 7, 'vk' => 89, 'ok' => 112);
$max_key = array_search(max($someArray), $someArray);
// $max_key would now be 'ok'