PHP如何计算数组中的重复值

时间:2011-08-11 07:05:24

标签: php arrays multidimensional-array duplicates

我想通过“groupid”计算数组中的重复值:

示例:

Array
(
    [0] => Array
        (
            [id] => 1230
            [groupid] => 177
            [activity_group_last] => 1229
            [name] => First name
        )

    [1] => Array
        (
            [id] => 1231
            [groupid] => 177
            [activity_group_last] => 1229
            [name] => Second name
        )

    [2] => Array
        (
            [id] => 1232
            [groupid] => 178
            [activity_group_last] => 1229
            [name] => Other name
        )

)

输出数组(2 groupid = 177和1 groupid = 178):

Array
(
    [0] => Array
        (
            [id] => 1231
            [groupid] => 177
            [activity_group_last] => 1229
            [name] => Second name
            [count] => 2

        )

    [1] => Array
        (
            [id] => 1232
            [groupid] => 178
            [activity_group_last] => 1229
            [name] => Other name
            [count] => 1
        )
)

谢谢!

2 个答案:

答案 0 :(得分:1)

如果$ value包含您的数组,则:

$count = array_count_values(array_map(function($item) {
    return $item['groupid'];
}, $value));
var_dump($count);

$_tmp = $count;
$unique = array_filter($value, function(&$item) use (&$_tmp, $count) {
    if (!--$_tmp[$item['groupid']]) {
        $item['count'] = $count[$item['groupid']];
        return true;
    }
    return false;
});
var_dump($unique);

结果:

array(2) {
  [1]=>
  array(5) {
    ["id"]=>
    int(1231)
    ["groupid"]=>
    int(177)
    ["activity_group_last"]=>
    int(1229)
    ["name"]=>
    string(11) "Second name"
    ["count"]=>
    int(2)
  }
  [2]=>
  array(5) {
    ["id"]=>
    int(1232)
    ["groupid"]=>
    int(178)
    ["activity_group_last"]=>
    int(1229)
    ["name"]=>
    string(10) "Other name"
    ["count"]=>
    int(1)
  }
}

答案 1 :(得分:0)

您也可以使用迭代功能执行此操作。如果您的输入数组存储在$ input中,并且您希望结果为$ output:

function remove_duplicates($input_array) {
  $output_array = array();            // Create an empty array for output
  foreach($input_array as $input) {   // Loop the input array
    if(array_key_exists($input['groupid'], $output_array)) {
      // We've already seen this groupid at least once
      // Increment count
      $input['count'] = $output_array[$input['groupid']]['count'] + 1;
    } else {
      // First time we've seen this groupid
      // Set count to 1
      $input['count'] = 1;
    }
    // Store data in $output_array, indexed by group_id
    $output_array[$input['groupid']] = $input;
  }
}

// This is your input array
$input = array(array('id'=>1230,'groupid'=>177,'activity_group_last'=>1229,'name'=>'First name'),
           array('id'=>1231,'groupid'=>177,'activity_group_last'=>1229,'name'=>'Second name'),
           array('id'=>1232,'groupid'=>178,'activity_group_last'=>1229,'name'=>'Other name'));
// This will set the output array correctly
$output = remove_duplicates($input);