phparrayssymfonyusort

Symfony2 - Trouble using usort inside a controller


I am trying to merge the contents of 2 arrays then use usort to get the posts with most views.

Trying to use usort to sort the contents of an array.

Am getting the follow error: ("Notice: Undefined property: Acme\DemoBundle\Entity\Article::$getViews in /.../PageController.php line 15")

Can someone point out what I am doing wrong?

Sort function inside of controller

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

Sidebar action

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

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

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

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

Solution

  • You don't have a property called getViews in your Article class.

    You probably have a property called views and a method getViews meaning you should call the actual method with the brackets like $article->getViews().