我有一个数组$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也是如此。密钥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
)
)
答案 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));