问题描述
问题
我有一个多维数组,类似于下面的数组.我试图实现的是一种从数组中查找和获取"Total"值最高的数组的方法,现在我知道有一个名为max
的函数,但不适用于像这样的多维数组.
I have a multidimensional array similar to the one below. What I'm trying to achieve is a way to find and retrieve from the array the one with the highest "Total" value, now I know there's a function called max
but that doesn't work with a multidimensional array like this.
我想做的是创建一个foreach循环并仅使用总数构建一个新数组,然后使用max
查找最大值,这将起作用,唯一的问题是检索其余部分与该最大值相关的数据.我也不确定这是否是最有效的方法.
What I've thought about doing is creating a foreach loop and building a new array with only the totals, then using max
to find the max value, which would work, the only issue would then be retrieving the rest of the data which relates to that max value. I'm not sure that's the most efficient way either.
有什么想法吗?
Array
(
[0] => Array
(
[Key1] => Key1
[Total] => 13
)
[1] => Array
(
[Key2] => Key2
[Total] => 117
)
[2] => Array
(
[Key3] => Key3
[Total] => 39
)
)
推荐答案
自PHP 5.5起,您可以使用array_column
来获取特定键的值数组,并将其最大化.
Since PHP 5.5 you can use array_column
to get an array of values for specific key, and max it.
max(array_column($array, 'Total'))
这篇关于在多维数组中找到最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!