循环遍历数组并删除重复的PHP

时间:2015-08-12 13:34:07

标签: php arrays

我有一个数组$rows,如下所示:

Array
(
    [0] => Array
        (
            [type] => post
            [object_id] => 1
            [language_id] => 1
            [score] => 2
        )

    [1] => Array
        (
            [type] => category
            [object_id] => 46
            [language_id] => 1
            [score] => 1
        )

    [2] => Array
        (
            [type] => product
            [object_id] => 50
            [language_id] => 1
            [score] => 1
        )

    [3] => Array
        (
            [type] => category
            [object_id] => 59
            [language_id] => 1
            [score] => 1
        )
    [4] => Array
        (
            [type] => post
            [object_id] => 1
            [language_id] => 1
            [score] => 1
        )
)

我需要遍历此数组,当重复的typeobject_id匹配时,增加分数并删除重复的数组。我似乎找不到办法来做到这一点。

使用上面的示例,密钥0包含type postobject_id 1,密钥4也是如此。密钥0 score应增加到本身+键4 score和键4应该被删除。

我的最终结果应如下所示:

Array
(
    [0] => Array
        (
            [type] => post
            [object_id] => 1
            [language_id] => 1
            [score] => 3
        )

    [1] => Array
        (
            [type] => category
            [object_id] => 46
            [language_id] => 1
            [score] => 1
        )

    [2] => Array
        (
            [type] => product
            [object_id] => 50
            [language_id] => 1
            [score] => 1
        )

    [3] => Array
        (
            [type] => category
            [object_id] => 59
            [language_id] => 1
            [score] => 1
        )
)

1 个答案:

答案 0 :(得分:1)

您可以使用foreach作为

来实现这一目标
$result = [];

foreach ($arr as $key => $value) {
    $hash = $value['type'];
    $hash1 = $value['object_id'];
    if (isset($result[$hash.$hash1]['type']) && isset($result[$hash.$hash1]['object_id'])) {
        $result[$hash.$hash1]['type'] = $value['type'];
        $result[$hash.$hash1]['object_id'] = $value['object_id'];
        $result[$hash.$hash1]['language_id'] = $value['language_id'];
        $result[$hash.$hash1]['score'] += $value['score'];
    } else {
        $result[$hash.$hash1]['type'] = $value['type'];
        $result[$hash.$hash1]['object_id'] = $value['object_id'];
        $result[$hash.$hash1]['language_id'] = $value['language_id'];
        $result[$hash.$hash1]['score'] = $value['score'];
    }
}

print_r(array_values($result));

Demo