PHP 从数组中获取最高值
我试图获取数组中的最大值,同时仍然保留项目标签。我知道我可以通过运行 sort() 来做到这一点,但如果我这样做,我只会丢失标签 - 这使得它对我所需要的毫无意义。这是数组:
array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
有什么想法吗?
I'm trying to get hold of the largest value in an array, while still preserving the item labels. I know I can do this by running sort(), but if I do so I simply lose the labels - which makes it pointless for what I need. Here's the array:
array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
您可以使用 max() 来获取最大值,但它只会返回一个没有相应索引的值的数组。然后,您可以使用 array_search() 查找相应的键。
输出:
如果有多个元素具有相同的值,则必须循环遍历数组才能获取所有键。
在不了解问题的情况下很难提出好的建议。为什么需要它?输入是什么,期望的输出是什么?
You could use max() for getting the largest value, but it will return just a value without an according index of array. Then, you could use array_search() to find the according key.
Output:
If there are multiple elements with the same value, you'll have to loop through array to get all the keys.
It's difficult to suggest something good without knowing the problem. Why do you need it? What is the input, what is the desired output?
最大价值=>试试这个,很简单
greatestValue=> try this its very easy
尝试一下。
<代码>
$data = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
$maxKey = 当前(array_keys($data, max($data)));
var_dump($maxKey);
Try it.
$data = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
$maxKey = current(array_keys($data, max($data)));
var_dump($maxKey);
找到最大的数,包括负数:
Find highest number, including negative:
asort()
是要走的路:asort()
is the way to go:您需要使用
ksort(数组("a"=>1,"b"=>2,"c"=>4,"d"=>5));
欲了解更多信息:http://www.w3schools.com/php/php_arrays_sort.asp
You need to use by
ksort(array("a"=>1,"b"=>2,"c"=>4,"d"=>5));
for more info: http://www.w3schools.com/php/php_arrays_sort.asp
这是练习中的解决方案:
Here a solution inside an exercise:
不使用 PHP 内置函数查找最大数
Find largest number without using built-in functions in PHP
尝试使用
asort()
。来自文档:
Try using
asort()
.From documentation:
不要对数组进行排序以获得最大值。
获取最大值:
获取对应的key:
Don't sort the array to get the largest value.
Get the max value:
Get the corresponding key:
如果您只想要数组中的最大值,请使用 max 函数。这将返回最大值,但不是相应的键。它不会改变原始数组。
如果你关心你可以做的密钥
(编辑以包括@binaryLV的建议)
If you just want the largest value in the array use the max function. This will return the largest value, although not the corresponding key. It does not change the original array.
If you care about the the key you could then do
(Edited to include @binaryLV's suggestion)
您正在寻找 asort()
You are looking for asort()