【问题标题】:Collection reduce and sum by key集合减少和按键求和
【发布时间】:2022-01-03 01:34:45
【问题描述】:

我有一个这样的集合:

#items: array:2 [
    0 => Illuminate\Support\Collection {
      #items: array:1 [
        1 => 3
      ]
    }
    1 => Illuminate\Support\Collection {
      #items: array:2 [
        1 => 1
        3 => 2
      ]
    }
    2 => Illuminate\Support\Collection {
      #items: array:2 [
        1 => 2
        2 => 2
      ]
    }
  ]

我想以某种方式将这个集合减少到一个带有sum 的条目。 结果应如下所示:

#items: array:1 [
    0 => Illuminate\Support\Collection {
      #items: array:2 [
        1 => 5
        2 => 2
        3 => 2
      ]
    }
  ]

如何使用 Laravel 实现这一目标?

谢谢!

【问题讨论】:

标签: laravel collections


【解决方案1】:

我设法得到了类似的结果:

$keys = $collection->map->keys()   // collection of collection of keys
                   ->flatten()     // collection of keys (with duplicates, unsorted)
                   ->unique()      // collection of keys (no duplicates, unsorted)
                   ->sort()        // collection of keys (no duplicates, sorted)
                                   // colleciton of [key => sum of values from original collection by key]
                   ->mapWithKeys(fn($item) => [$item => $collection->sum($item)]);

dump($keys); 返回:

Illuminate\Support\Collection {
  #items: array:3 [
    1 => 6
    2 => 2
    3 => 2
  ]
}

dump([$keys]); 返回:

array:1 [
  0 => Illuminate\Support\Collection {
    #items: array:3 [
      1 => 6
      2 => 2
      3 => 2
    ]
  }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2015-07-08
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多