在多维数组中查找最大值

2021-12-21 00:00:00 multidimensional-array max php

问题

我有一个类似于下面的多维数组.我想要实现的是一种从数组中查找和检索具有最高总"值的方法,现在我知道有一个名为 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'))

相关文章