Symfony 2. usort() 不起作用
Symfony 2. Doesn't work usort()
伙计们!我需要帮助。 Usort() 在 symfony2 class.
中不起作用
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; }
}),
代码续...
怎么了?
正如@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,
]);
伙计们!我需要帮助。 Usort() 在 symfony2 class.
中不起作用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; }
}),
代码续...
怎么了?
正如@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,
]);