問題描述
問題
我有一個類似于下面的多維數組.我想要實現的是一種從數組中查找和檢索具有最高總"值的方法,現在我知道有一個名為 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'))
這篇關于在多維數組中查找最大值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!