家伙!我需要帮助。 Usort()在symfony2类中不起作用。
class UserController extends Controller
{ ...
/**
* @Route("/dashboard", name="dashboard")
*/
public function dashboard()
{
SQL查询:
/** @var \MyBundle\Entity\User $user */
$user = $this->getDoctrine()
->getRepository('MyBundle:User')
->find($this->getUser()->getId());
/** @var \MyBundle\Entity\Event[] $events */
$events = $this->getDoctrine()
->getRepository('MyBundle:Event')
->findBy(['creator' => $user->getId()]);
数据阵列:
$allEvents = [];
foreach ($events as $event) {
$allEvents[] = $event;
}
foreach ($user->getEvents() as $event) {
$allEvents[] = $event;
}
树枝的结果:
return $this->render(
'MyBundle:User:dashboard.html.twig',
[ 'allEvents' => usort($allEvents, function( $a, $b )
{ if ( $a["schedule"] == $b["schedule"] )
{ return 0; }
else
{ return ( $a["schedule"] < $b["schedule"] ) ? -1 : 1; }
}),
代码延续......
出了什么问题?
答案 0 :(得分:2)
正如@ Rizier123所说,usort()
returns a boolean。
所以试试这个:
// First, sort the array
usort($allEvents, function($a, $b) { // $a and $b are instances of MyBundle\Entity\Event
// this depends on your object, just call the right function
if ($a->getSchedule() == $b->getSchedule()) {
return 0;
}
return $a->getSchedule() < $b->getSchedule() ? -1 : 1;
});
// Then, use the sorted array in your template
return $this->render('MyBundle:User:dashboard.html.twig', [
'allEvents' => $allEvents,
]);