2015-09-07 74 views
0

陣列:的Symfony 2.日期時間數組排序數據

$allEvents = [];   
    foreach ($events as $event) { 
      $allEvents[] = $event; 
    } 
    foreach ($user->getEvents() as $event) { 
      $allEvents[] = $event; 
    } 

結果小枝:

 return $this->render(
     'MyBundle:User:dashboard.html.twig', 
     [ 'allEvents' => $allEvents, 
      'user' => $user ] 
     ); 

的var_dump allEvents結果:

array:5 [ 0 => Event { 
       id: 26 
       title: "test action" 
       category: Category 
       creator: User 
       ***schedule***: DateTime { 
         "date": "2015-12-24 17:10:00.000000" 
         "timezone_type": ... 
         "timezone": ... 
         } 
       } 
      1 => Event {...} 
      2 => Event {...} 
      3 => Event {...} 
      4 => Event {...} 
     ] 

問:我該怎麼辦按時間表排序數組(有些像ASC或DESC排序)?

回答

1

你可以使用PHP的usort功能如下(我已經編輯了答案給你看更清晰):

編輯:

$allSortedEvents = usort($allEvents, function($a, $b){ 
    if ($a->getSchedule() == $b->getSchedule()) 
    { 
     return 0; 
    } 
    else 
    { 
     return ($a->getSchedule() < $b->getSchedule()) ? -1 : 1; 
    } 
});  

併發送至爲樹枝:

return $this->render(
    'MyBundle:User:dashboard.html.twig', 
    [ 'allEvents' => $allSortedEvents, 
     'user' => $user ] 
    ); 
+0

試過了。錯誤:'警告:usort()期望參數2是一個有效的回調函數'customSort'未找到或無效的函數名稱'。有另一個想法? – chrisperk

+0

你在哪裏寫了customSort函數? – Airam

+1

解決方案:'$ a [「schedule」]'替換爲'$ a-> getSchedule()'和其他 – chrisperk