我有一类有用户评分的新闻。我的目标是找到所有评分的平均值,我使用的是 MongoDB。我试图找到一个已经用于平均内置的函数,但我找不到。所以我计划 使用 count() 函数,然后获取数组集合中所有元素的总和,并将总和除以 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 是我陷入困境的地方
最佳答案
不,没有内置方法来计算它,但您可以将其转换为常规数组,并很容易地使用数组函数。
假设您的 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
。
关于php - 在 Symfony、MongoDB 中查找 ArrayCollection 中元素的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64318986/