php 获取PHP数组中的最小值并获取对应的key
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11964357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get min value in PHP array and get corresponding key
提问by Timothy Clemans
I have an array, Array ( [0] => 3 [1] => 0 ). I want PHP code that returns 1 because 1's value is the lowest. How do I do this? This is for the code at https://github.com/timothyclemans/RoboQWOP/commit/e205401a56b49e8b31f089aaee0042f8de49a47d
我有一个数组 Array ( [0] => 3 [1] => 0 )。我想要返回 1 的 PHP 代码,因为 1 的值是最低的。我该怎么做呢?这是https://github.com/timothyclemans/RoboQWOP/commit/e205401a56b49e8b31f089aaee0042f8de49a47d 上的代码
回答by Trott
This will return the first index that has the minimum value in the array. It is useful if you only need one index when the array has multiple instances of the minimum value:
这将返回数组中具有最小值的第一个索引。当数组有多个最小值的实例时,如果您只需要一个索引,这会很有用:
$index = array_search(min($my_array), $my_array);
This will return an array of all the indexes that have the minimum value in the array. It is useful if you need all the instances of the minimum value but may be slightly less efficient than the solution above:
这将返回一个数组,其中包含数组中具有最小值的所有索引。如果您需要最小值的所有实例,这很有用,但可能比上面的解决方案效率稍低:
$index = array_keys($my_array, min($my_array));
回答by KingKongFrog
array_keys($array, min($array));
回答by HandiworkNYC.com
http://php.net/manual/en/function.min.php
http://php.net/manual/en/function.min.php
http://php.net/manual/en/function.array-search.php
http://php.net/manual/en/function.array-search.php
$array = array( [0] => 3, [1] => 0);
$min = min($array);
$index = array_search($min, $array);
Should return 1
应该返回 1
回答by User 99x
The below example would help you.
下面的例子会对你有所帮助。
$values=array(3,0,4,2,1);
$min_value_key=array_keys($values, min($values));
echo $min_value_key;
Hope this helps.
希望这可以帮助。

