The array that I use is an array merged from three different arrays (3 different mysql results). Each array is an associative array with a few fields and the count
field is the field I need.
The following piece of array is a double entry. I want to check the array and check if there are duplicates ( id
field) and calculate the sum of the count field. What would be the best-practice to solve this issue?
array(21) {
[2] => array(6) {
["id"] => string(2) "71"
["artist"] => string(7) "Arsenal"
["title"] => string(10) "Oyebo Soul"
["genres_id"] => string(2) "13"
["mbid"] => string(36) "0048d294-1557-4e05-8c82-8bc3f8f11923"
["count"] => string(1) "4"
}
[3] => array(6) {
["count"] => string(1) "3"
["id"] => string(2) "71"
["artist"] => string(7) "Arsenal"
["title"] => string(10) "Oyebo Soul"
["genres_id"] => string(2) "13"
["mbid"] => string(36) "0048d294-1557-4e05-8c82-8bc3f8f11923"
}
The result would be this:
[3] => array(6) {
["count"] => string(1) "7"
["id"] => string(2) "71"
["artist"] => string(7) "Arsenal"
["title"] => string(10) "Oyebo Soul"
["genres_id"] => string(2) "13"
["mbid"] => string(36) "0048d294-1557-4e05-8c82-8bc3f8f11923"
}
Hope this makes any sense. Thanks in advance
There's bound to be a ton of different ways to approach this problem, but the first one that popped into my head was to make use of array_reduce()
on each set of "duplicate" albums:
// Group and index the albums by 'mbid'...
$indexed = array();
foreach ($albums as $album) {
$indexed[$album['mbid']][] = $album;
}
// Reduce all the album groups by simply totaling their 'count's...
$indexed = array_map(function($albums) {
return array_reduce($albums, function($a, $b) {
$a['count'] += $b['count'];
return $a;
});
}, $indexed);
Note: This solution assumes that all the information in each album duplicate is identical except the count
, as is the case in your example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.