【问题标题】:Symfony2 - Trouble using usort inside a controllerSymfony2 - 在控制器中使用 usort 时出现问题
【发布时间】:2014-07-17 08:06:55
【问题描述】:

我正在尝试合并 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'));

【问题讨论】:

    标签: arrays symfony usort


    【解决方案1】:

    getViews 是用于访问实体PostArticle 的属性视图的getter 方法。因此,在访问它时,您应该以$articles-&gt;getViews() 的身份访问它。

    但是,如果您只是想比较两个实体的属性views,则使用它们的属性名称而不是它们的 getter 来比较它们

    假设views是属性的名字,调用应该是这样的:

    $posts-&gt;views$articles-&gt;views

    【讨论】:

    • 感谢 Ankit 的解释,但 Qoop 是第一个。
    • 实际上我现在正尝试在其中添加 2 个实体。但我得到一个错误。 popularSort function--return $articles-&gt;getViews() == $posts-&gt;getViews() &amp;&amp; $articles2-&gt;getViews() == $posts2s-&gt;getViews() ? 0 : ( $articles2-&gt;getViews() &lt; $posts2-&gt;getViews() &amp;&amp; $predictions-&gt;getViews() &lt; $scorings-&gt;getViews()) ? 1: -1; 并收到此错误:"Warning: Missing argument 3 for Acme\DemoBundle\Controller\PageController::popularSort() 任何想法?
    • 这个问题一般是由于函数定义和函数调用不一致造成的。您在上述评论中粘贴的功能似乎没有校准。我建议发布一个新问题。或在此站点上搜索现有问题
    • 错误不是你定义函数的地方错误是调用这个函数函数的地方。该函数期望更多参数,然后实际传递
    • 嗯,我已经更新了 array_merge 以合并其他 2 个数组,我在使用 usort 时缺少什么?
    【解决方案2】:

    您的 Article 类中没有名为 getViews 的属性。

    您可能有一个名为views 的属性和一个方法getViews,这意味着您应该调用带有括号的实际方法,例如$article-&gt;getViews()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-03
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多