1

我使用的数组是从三个不同的数组(3 个不同的 mysql 结果)合并而来的数组。每个数组都是一个具有几个字段的关联数组,该count字段是我需要的字段。

下面的数组是一个复式。我想检查数组并检查是否有重复项(id字段)并计算计数字段的总和。解决此问题的最佳做法是什么?

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"
}

结果将是这样的:

[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"
}

希望这有任何意义。提前致谢

4

1 回答 1

0

肯定会有很多不同的方法来解决这个问题,但我脑海中浮现的第一个方法是array_reduce()在每组“重复”专辑中使用:

// 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.

于 2012-11-10T21:50:27.837 回答