php - 在 Symfony、MongoDB 中查找 ArrayCollection 中元素的平均值

标签 php mongodb symfony average

我有一类有用户评分的新闻。我的目标是找到所有评分的平均值,我使用的是 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

Reference for the Collectionmethods

关于php - 在 Symfony、MongoDB 中查找 ArrayCollection 中元素的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64318986/

相关文章:

node.js - 在 mongodb 中存储来自 nodejs 的 settimeout id

php - Symfony2 表单,与实体不匹配

javascript - DataTables(jQuery 的表格插件)在导航离开和返回 DataTable 时从上次中断的地方继续

php - 如何在 MySQL 选择查询中编写正则表达式?

mongodb - 如何获得收藏的独特值(value)

mongodb - 从未调用 TestMain m.Run() 后的拆解函数

php - Silex:在防火墙外的路由上获取经过身份验证的用户信息

php - 使用 php 调整图像大小

php - 如何显示来自mysql db的多行逗号分隔值

php - 如何从数据库中回显表行(php)