[英]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
)
)
我需要遍歷此數組,當重復的type
和object_id
匹配時,增加分數並刪除重復的數組。 我似乎找不到解決方法。
在上面的示例中,鍵0的type
post
和object_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.