数组中的重复项

时间:2011-11-15 15:56:17

标签: php arrays duplicates

我有一个如下所示的数组:

$array[1]['first__name'] = 'john'; 
$array[1]['last_name']   = 'anderson'; 
$array[1]['sum']         = 100; 

$array[2]['first__name'] = 'john'; 
$array[2]['last_name']   = 'anderson'; 
$array[2]['sum']         = 200; 

$array[3]['first__name'] = 'julie'; 
$array[3]['last_name']   = 'Scott'; 
$array[3]['sum']         = 300; 

$array[4]['first__name'] = 'Eva'; 
$array[4]['last_name']   = 'Scott'; 
$array[4]['sum']         = 300; 

$array[5]['first__name'] = 'john'; 
$array[5]['last_name']   = 'anderson'; 
$array[5]['sum']         = 300; 

我想比较总和first_name = johnlast_name = anderson并保存最高值。其余的我想删除。

3 个答案:

答案 0 :(得分:1)

$highest = 0;
foreach ($array as $v){
  if ($v['first_name'] == 'john' && $v['last_name'] == 'anderson'){
    if ($v['sum'] > $highest){$highest = $v['sum'];
  }
}
echo $highest;

答案 1 :(得分:0)

这个怎么样?

$scores = array();
foreach( $array as $row ) {
    $name = $row['first_name'] . ' ' . $row['last_name'];
    if( !isset( $scores[$name] ) || ( $row['sum'] > $scores[$name] ) ) {
        $scores[$name] = $row['sum'];
    }
}

答案 2 :(得分:0)

这也有效:)

$array[1]['first_name'] = 'john'; 
$array[1]['last_name']   = 'anderson'; 
$array[1]['sum']         = 100; 

$array[2]['first_name'] = 'john'; 
$array[2]['last_name']   = 'anderson'; 
$array[2]['sum']         = 300; 

$array[3]['first_name'] = 'julie'; 
$array[3]['last_name']   = 'Scott'; 
$array[3]['sum']         = 300; 

$array[4]['first_name'] = 'Eva'; 
$array[4]['last_name']   = 'Scott'; 
$array[4]['sum']         = 300; 

$array[5]['first_name'] = 'john'; 
$array[5]['last_name']   = 'anderson'; 
$array[5]['sum']         = 200; 

$cond = array('first_name' => 'john', 'last_name' => 'anderson');

array_walk($array, function($node, $key) use ($cond, &$array) {
    foreach($cond as $k => $v) {
        if(!isset($node[$k]) || $node[$k] != $v) {
            unset($array[$key]);
        }
    }
});
uasort($array, function($a, $b){
    return intval($a['sum']) - intval($b['sum']);
});

$result = end($array);