本文介绍了在关联数组中查找最小值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在PHP中,说您有一个像这样的关联数组:
In PHP, say that you have an associative array like this:
$pets = array(
"cats" => 1,
"dogs" => 2,
"fish" => 3
);
如何找到具有最低值的密钥?在这里,我要寻找cats
.
我错过了一些内置的PHP函数吗?如果有一个解决方案可以说明几个相同的值,那也很好,如下:
Is there some built in PHP function that I've missed which does this? It would also be great if there was a solution that accounted for several values being identical, as below:
$pets = array(
"cats" => 1,
"dogs" => 1,
"fish" => 2
);
上面,我不介意它是否只是输出; cats
或dogs
.
Above, I wouldn't mind if it just output either; cats
or dogs
.
谢谢.
推荐答案
array_keys
是您的朋友:
array_keys
is your friend:
$pets = array(
"cats" => 1,
"dogs" => 2,
"fish" => 3
);
array_keys($pets, min($pets)); # array('cats')
P.S.:在SO的某处有一个dup(它是max
而不是min
,但我可以清楚地记住它).
P.S.: there is a dup here somewhere on SO (it had max
instead of min
, but I can distinctly remember it).
这篇关于在关联数组中查找最小值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!