簡體   English   中英

遍歷數組並刪除重復的PHP

[英]Loop through array and delete duplicates PHP

我有一個數組$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的type也是如此。鍵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
        )
)

您只需使用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));

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM