0

我想删除重复的数组,同时在原始数组中添加一个新的键“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] =>
        )

)
4

1 回答 1

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

结果包含你想要的。

于 2013-08-03T03:48:42.610 回答