PHP多维数组找到重复的最大值

时间:2016-06-14 17:12:34

标签: php arrays multidimensional-array

我有一个多维数组,我希望找到key =>值的最大值,但只能找到重复的特定键,并创建一个具有该最大值的新key =>值。

通过显示初始数组和预期结果来解释更容易

$data = array(
 0 => array('id' => '1a','info'=>'abc','level'=>1),
 1 => array('id' => '1a','info'=>'xyz','level'=>3),
 2 => array('id' => '2b','info'=>'uvw','level'=>2),
 3 => array('id' => '3c','info'=>'str','level'=>1),
 4 => array('id' => '3c','info'=>'str2','level'=>2),
 5 => array('id' => '4d','info'=>'uvw1','level'=>1),
);



$result = array(
  0 => array('id' => '1a','info'=>'abc','level'=>1,'max_level'=>3),
  1 => array('id' => '1a','info'=>'xyz','level'=>3,'max_level'=>3),
  2 => array('id' => '2b','info'=>'uvw','level'=>2,'max_level'=>2),
  3 => array('id' => '3c','info'=>'str','level'=>1,'max_level'=>2),
  4 => array('id' => '3c','info'=>'str2','level'=>2,'max_level'=>2),
  5 => array('id' => '4d','info'=>'uvw1','level'=>1,'max_level'=>1),
);

我已经研究过找到重复的'id'和max'level'值,但我无法将两者结合起来并保留非重复值。

2 个答案:

答案 0 :(得分:1)

使用array_walkmax函数的解决方案:

array_walk($data, function($v) use(&$max_levels){ $max_levels[$v['id']][] = $v['level']; });
foreach ($data as &$v) {
    $v['max_level'] = max($max_levels[$v['id']]);    
}

print_r($data);

https://eval.in/588966

答案 1 :(得分:0)

因此,您的任务分为两部分:

// first - find maximum level of every `id`
$max_values = array();
foreach ($data as $v) {
    if (!isset($max_values[$v['id']]) || $max_values[$v['id']] < $v['level']) {
        $max_values[$v['id']] = $v['level'];
    }
}

// second - add this level to $data
foreach ($data as &$v) {
    $v['max_level'] = $max_values[$v['id']];
}