我想按日期时间变量对对象数组进行排序,日期位于未来,并且我希望最接近当前日期的日期作为第一个日期。
我在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');
对此数组进行排序的正确方法是什么?
由于我不知道错误指的是哪一行,所以这是黑暗中的一个小镜头:
取代
return $a['date']->format('U') - $b['date']->format('U');
跟
return $a->date->format('U') - $b->date->format('U');
- 您的数据库架构似乎很糟糕。
LoginLoginBundle:Matchgame
有两个属性hometeam
和awayteam
,用于存储关联团队的名称。为什么不是 ID?这是一个一对一/多对一的协会,应该通过原则来管理。 -
->findByUserUserid
你想得到一行。所以它应该是->findOneByUserUserid
(但为什么user_userid?? - 数据库针对排序进行了大量优化。让数据库完成这项工作。
- 您可以编写非常复杂的 DQL 查询。为您的方法编写自定义表存储库。
此查询应执行所需的操作,但再次:首先改进数据库架构!
$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();