代码之家  ›  专栏  ›  技术社区  ›  Jaroslav Klimčík

Laravel集合中的增量

  •  0
  • Jaroslav Klimčík  · 技术社区  · 6 年前

    我有一个集合,如果满足条件,我想增加值。我想用 map() 方法来迭代并返回具有总计数的数组(或集合)。到目前为止,我有:

       $counts = [
            'notChecked' => 0,
            'published' => 0,
            'total' => 0
        ];
    
        $this->reviewPhotosRepository->getByHotelId($hotel_id)->map(function($photo) use (&$counts) {
            $photo->checked ?: $counts['notChecked']++;
            $photo->published ?: $counts['published']++;
            $counts['total']++;
        });
    
        return $counts;
    

    它的工作,但我认为它看起来很奇怪,这不是这样一个'拉维利'的方式。有没有其他办法让它看起来更好一点?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Travis Britz    6 年前

    map() reduce()

    return $this->reviewPhotosRepository
        ->getByHotelId($hotel_id)
        ->reduce(function ($carry, $item) {
            $carry['notChecked'] += $item['checked'] ? 1 : 0;
            $carry['published'] += $item['published'] ? 1 : 0;
            $carry['total'] += 1;
            return $carry;
        }, [
            'notChecked' => 0,
            'published' => 0,
            'total' => 0
        ]);