多维数组:删除重复数据并将它们计时到原始数组

时间:2013-08-03 03:38:35

标签: php arrays multidimensional-array

我想删除重复的数组,同时添加一个新的密钥'duplicates'和重复的总数到原始数组。使用PHP执行此操作的最佳方法是什么?

Array
(
    [0] => Array
        (
            [w] => 10
            [r] => 10
            [e] => 489
        )

    [1] => Array
        (
            [w] => 10
            [r] => 10
            [e] => 489
        )

    [2] => Array
        (
            [w] => 10
            [r] => 10
            [e] => 489
        )

    [3] => Array
        (
            [w] => 20
            [r] => 20
            [e] => 489
        )

    [4] => Array
        (
            [w] => 10
            [r] => 10
            [e] =>
        )

)

会变成:

Array
(
    [0] => Array
        (
            [w] => 10
            [r] => 10
            [e] => 489
            [duplicates] => 2
        )

    [3] => Array
        (
            [w] => 20
            [r] => 20
            [e] => 489
        )

    [4] => Array
        (
            [w] => 10
            [r] => 10
            [e] =>
        )

)

1 个答案:

答案 0 :(得分:0)

您可以获取唯一数组,然后与原始数组进行比较:

$result = array_map("unserialize", array_unique(array_map("serialize", $input)));
foreach ($result as &$arr) {
    $cnt = 0;
    foreach ($input as $inArr) {
        if ($arr == $inArr) {
            $cnt++;
        }
    }
    if ($cnt > 1) {
        $arr['duplicates'] = $cnt - 1;
    }
}

The result contains what you want.