php 在多维数组中查找最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17339421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find highest value in multidimensional array
提问by Karl
The Problem
问题
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.
我有一个类似于下面的多维数组。我想要实现的是一种从数组中查找和检索具有最高“总”值的方法,现在我知道有一个函数被调用,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.
我想做的是创建一个 foreach 循环并构建一个仅包含总数的新数组,然后使用它max
来查找最大值,这将起作用,唯一的问题是检索与此相关的其余数据最大值。我也不确定这是最有效的方法。
Any ideas?
有任何想法吗?
Array
(
[0] => Array
(
[Key1] => Key1
[Total] => 13
)
[1] => Array
(
[Key2] => Key2
[Total] => 117
)
[2] => Array
(
[Key3] => Key3
[Total] => 39
)
)
回答by Astrus
Since PHP 5.5 you can use array_column
to get an array of values for specific key, and max it.
从 PHP 5.5 开始,您可以使用array_column
获取特定键的值数组,并将其最大化。
max(array_column($array, 'Total'))
max(array_column($array, 'Total'))
回答by Baba
Just do a simple loop
and compare values or use array_reduce
只需做一个simple loop
并比较值或使用array_reduce
$data = array_reduce($data, function ($a, $b) {
return @$a['Total'] > $b['Total'] ? $a : $b ;
});
print_r($data);
回答by Robert
It's so basic algorithm.
这是非常基本的算法。
$max = -9999999; //will hold max val
$found_item = null; //will hold item with max val;
foreach($arr as $k=>$v)
{
if($v['Total']>$max)
{
$max = $v['Total'];
$found_item = $v;
}
}
echo "max value is $max";
print_r($found_item);
回答by mister martin
I know this question is old, but I'm providing the following answer in response to another question that pointed here after being marked as a duplicate. This is another alternative I don't see mentioned in the current answers.
我知道这个问题很旧,但我提供以下答案以回应在被标记为重复后指向此处的另一个问题。这是我在当前答案中没有看到的另一种选择。
I know there's a function called max but that doesn't work with a multidimensional array like this.
我知道有一个名为 max 的函数,但它不适用于像这样的多维数组。
You can get around that with array_column
which makes getting the maximum value very easy:
你可以解决这个问题,array_column
这使得获得最大值变得非常容易:
$arr = [['message_id' => 1,
'points' => 3],
['message_id' => 2,
'points' => 2],
['message_id' => 3,
'points' => 2]];
// max value
$max = max(array_column($arr, 'points'));
Getting the associative key is where it gets a little more tricky, considering that you might actually want multiple keys (if $max
matches more than one value). You can do this with an anonymous function inside array_map
, and use array_filter
to remove the null
values:
考虑到您实际上可能需要多个键(如果$max
匹配多个值),获取关联键会变得更加棘手。您可以array_map
使用内部的匿名函数执行此操作,并用于array_filter
删除null
值:
// keys of max value
$keys = array_filter(array_map(function ($arr) use ($max) {
return $arr['points'] == $max ? $arr['message_id'] : null;
}, $arr));
Output:
输出:
array(1) {
[0]=>
int(1)
}
If you do end up with multiples keys but are only interested in the first match found, then simply reference $keys[0]
.
如果您最终得到多个键但只对找到的第一个匹配项感兴趣,则只需引用$keys[0]
.
回答by bystwn22
another simple method will be
另一个简单的方法是
$max = array_map( function( $arr ) {
global $last;
return (int)( ( $arr["Total"] > $last ) ? $arr["Total"] : $last );
}, $array );
print_r( max( $max ) );
回答by Nabi K.A.Z.
<?php
$myarray = array(
0 => array(
'Key1' => 'Key1',
'Total' => 13,
),
1 => array(
'Key2' => 'Key2',
'Total' => 117,
),
2 => array(
'Key2' => 'Key3',
'Total' => 39,
),
);
$out = array();
foreach ($myarray as $item) {
$out[] = $item['Total'];
}
echo max($out); //117
unset($out, $item);
回答by katona.abel
Can be done using array_walk(array_walk_recursive if needed)
可以使用 array_walk(array_walk_recursive 如果需要)
$arr is the array you want to search in
$arr 是您要搜索的数组
$largestElement = null;
array_walk($arr, function(&$item, $key) use (&$largestElement) {
if (!is_array($largestElement) || $largestElement["Total"] < $item["Total"]) {
$largestElement = $item;
}
});
回答by Umair Khan
You can use php usort function: http://php.net/manual/en/function.usort.php
您可以使用 php usort 函数:http: //php.net/manual/en/function.usort.php
A pretty illustrative example is given here:
这里给出了一个非常说明性的例子:
<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
echo "$fruits[$key]: " . $value["fruit"] . "\n";
}
?>
So it will sort the max value to the last array index.
所以它将最大值排序到最后一个数组索引。
Output:
输出:
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons
This example is given on aforementioned link
这个例子在上述链接上给出
回答by wLc
array_reduceaccepts a 3rd "initial" parameter. Use this to avoid the bad practice of using "@" error suppression :
array_reduce接受第三个“初始”参数。使用它可以避免使用“@”错误抑制的不良做法:
$data = array_reduce($data, function ($a, $b) {
return $a['Total'] > $b['Total'] ? $a : $b ;
},['Total' => 0]);
print_r($data);
PHP 7.4
PHP 7.4
$data = array_reduce($data, fn(a,b) => $a['Total'] > $b['Total'] ? $a : $b, ['Total' => 0]);