在 Symfony 中查找 ArrayCollection 中元素的平均值,MongoDB

Finding the average of elements in ArrayCollection in Symfony, MongoDB

我有 class 条新闻有用户评分。我的目标是找到所有评分的平均值,我使用的是 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 是我卡住的地方

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

假设您的 Rating class 有一个名为 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