2016-06-14 64 views
-1

我有一個多維數組,我希望找到一個key => value的最大值,但只有重複的特定鍵並創建一個新的key =>具有該最大值的值。PHP多維數組找到最大重複數

它更容易通過展示

$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), 
); 

我已經研究過尋找重複的「身份證」和max'level」值初始陣列和預期的結果來解釋,但我沒能將兩者結合在一起並保持不重複。

+0

所以,你嘗試過什麼嗎? –

回答

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']]; 
} 
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

+0

謝謝!這是我遇到的array_walk位。 – NorthSide

+0

@NorthSide,不客氣 – RomanPerekhrest