我想按日期时间变量对对象数组进行排序,日期位于将来,我希望将最接近当前日期的日期作为第一个日期。
我在symfony2中使用以下控制分数:
public function fixturesAction(){
if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
throw $this->createAccessDeniedException('Unable to access this page!');
}
$user = $this->get('security.context')->getToken()->getUser();
$team = $this->getDoctrine()
->getRepository('LoginLoginBundle:Team')
->findByUserUserid($user->getUserid());
$matchGamesHome = $this->getDoctrine()
->getRepository('LoginLoginBundle:Matchgame')
->findByHometeam($team[0]->getName());
$matchGamesAway = $this->getDoctrine()
->getRepository('LoginLoginBundle:Matchgame')
->findByAwayteam($team[0]->getName());
$matchGames = array_merge($matchGamesHome, $matchGamesAway);
$sorted = usort($matchGames, function($a, $b) {
return $a->date->format('U') - $b->date->format('U');
});
return $this->render('LoginLoginBundle:Default:fixtures.html.twig', array("matchArray"=>$sorted));
}
我在哪里进行排序:
$sorted = usort($matchGames, function($a, $b) {
return $a->date->format('U') - $b->date->format('U');
});
这会产生以下错误:
Error: Cannot access private property Login\LoginBundle\Entity\Matchgame::$date in C:\wamp\www\SocProNetbeans\src\Login\LoginBundle\Controller\DefaultController.php line 675
第675行如下:
return $a->date->format('U') - $b->date->format('U');
对此数组进行排序的正确方法是什么?
答案 0 :(得分:2)
由于我不知道错误所说的是哪一行,所以在黑暗中这是一个小小的镜头:
替换
return $a['date']->format('U') - $b['date']->format('U');
与
return $a->date->format('U') - $b->date->format('U');
答案 1 :(得分:0)
LoginLoginBundle:Matchgame
有两个属性hometeam
和awayteam
,用于存储关联团队的名称。为什么不 ID ?这是OneToMany/ManyToOne association,应由学说管理。->findByUserUserid
你想获得一排。所以它应该是->findOneByUserUserid
(但为什么是user_userid ??)此查询应该执行您想要的操作,但请再次:首先改进数据库架构!
$query = $em->createQuery('
SELECT g
FROM LoginLoginBundle:Matchgame g
WHERE g.hometeam = :hometeam
OR g.awayteam = :awayteam
ORDER BY g.date ASC
');
$query->setParameter('hometeam', $team);
$query->setParameter('awayteam', $team);
$matches = $query->getResult();