【问题标题】:Increment in Laravel collectionLaravel 集合中的增量
【发布时间】:2019-04-08 05:09:30
【问题描述】:

我有一个集合,如果满足条件,我想增加值。我想使用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;

它有效,但我认为它看起来很奇怪,它不是一种“laravelish”方式。有没有其他的选择让它看起来更好一点?

【问题讨论】:

    标签: php loops collections increment laravel-5.7


    【解决方案1】:

    您可以使用reduce(),而不是map()

    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
        ]);
    

    更好吗?好吧,你知道,这只是你的意见,伙计。

    【讨论】:

      猜你喜欢
      • 2017-09-27
      • 1970-01-01
      • 2015-11-01
      • 2015-07-01
      • 2021-08-04
      • 2015-11-24
      • 2019-05-16
      • 2021-07-17
      • 2020-09-04
      相关资源
      最近更新 更多