Symfony2 - 在控制器中使用usort时遇到麻烦

时间:2014-07-17 08:06:55

标签: arrays symfony usort

我正在尝试合并2个数组的内容,然后使用usort获取大多数视图的帖子。

尝试使用usort对数组的内容进行排序。

我收到了以下错误: ("Notice: Undefined property: Acme\DemoBundle\Entity\Article::$getViews in /.../PageController.php line 15")

有人可以指出我做错了吗?

对控制器内部的功能进行排序

private static function popularSort($articles, $posts, $articles2, $posts2)
{
    return $articles->getViews() == $posts->getViews() ? 0 : ( $articles->getViews() < $posts->getViews()) ? 1: -1;
}

补充工具栏

$articles = $this->getDoctrine()->getRepository('AcmeDemoBundle:Article')
    ->getArticles();

$posts = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post')
    ->getPosts();

$popular = array_merge($articles, $posts);

usort($popular, array($this, 'popularSort'));

2 个答案:

答案 0 :(得分:1)

getViews是一种用于访问实体PostArticle的属性视图的getter方法。因此,在访问它时,您应该以{{1​​}}访问它。

但是,如果您只想比较两个实体的属性$articles->getViews(),请使用其属性名称而不是其getter来比较它们

假设视图是属性的名称,则调用应该类似于:

views$posts->views

答案 1 :(得分:0)

您的getViews课程中没有名为Article的媒体资源。

您可能有一个名为views的属性和一个方法getViews,这意味着您应该使用$article->getViews()这样的括号调用实际方法。