【问题标题】:Finding the average of elements in ArrayCollection in Symfony, MongoDB在 Symfony、MongoDB 中查找 ArrayCollection 中元素的平均值
【发布时间】:2020-10-12 13:37:06
【问题描述】:

我有一类有用户评分的新闻。我的目标是找到所有评分的平均值,我使用的是 MongoDB。我试图找到一个平均内置的功能,但我找不到。所以我打算 使用 count() 函数,然后获取数组集合中所有元素的总和,然后将总和除以计数,但是总和效果不佳,是否有内置函数?如果不是,我如何迭代 PHP 数组集合并添加值

 public function __construct()
    {
        $this->positiveFeedback = new ArrayCollection();
        $this->negativeFeedback = new ArrayCollection();
        $this->rating = new ArrayCollection();
    }    

 /**
     * @return Collection|Rating[]
     */
    public function getRating(): Collection
    {
        return $this->rating;
    }

    public function addRating(Rating $rating): self
    {
        if (!$this->rating->contains($rating)) {
            $this->rating[] = $rating;
            $rating->setNews($this);
        }

        return $this;
    }

    public function removeRAting(Rating $rating): self
    {
        if ($this->rating->contains($rating)) {
            $this->rating->removeElement($rating);
            // set the owning side to null (unless already changed)
            if ($rating->getNews() === $this) {
                $rating->setNews(null);
            }
        }

        return $this;
    }
 /**
     * Get the value of RatingAverage
     */ 
    public function getRatingAverage()
    {
        $ratingsNumber =  $this->getRating()->count();
        $ratingSum = $this->getRating()->getValues();

    }

getRatingAverage 是我卡住的地方

【问题讨论】:

    标签: php mongodb symfony average


    【解决方案1】:

    不,没有内置方法来计算它,但您可以将其转换为常规数组并很容易使用数组函数。

    假设您的 Rating 类有一个名为 score 的属性:

    public function getRatingAverage()
    {
        $ratingsNumber = $this->getRating()->count();
    
        if (0 === $ratingsNumber)
            return;
    
        $scores = $this->getRating()
            // Get a new collection containing only the score values
            ->map(function($rating) { return $rating->getScore(); })
            // Transform into an array
            ->getValues();
    
        $ratingSum = array_sum($scores);
        $ratingAvg = $ratingSum / $ratingsNumber;
    
        return $ratingAvg;
    }
    

    不过,Collection 是可迭代的,所以如果你想循环它,你可以使用普通的 foreach

    Reference for the Collectionmethods

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-14
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      相关资源
      最近更新 更多