Sort an array of objects in Symfony based on date and time

// Suppose Entity Notes has access to the 'creationdate' and 'getCreationDate ()' properties.

  DefaultController extends Controller {
         public function indexAction(){
           $em = $this->getDoctrine()->getManager();
           $repository = $em->getRepository('Bundle:Notes');
           $notes = $repository->findBy(array('userid' => $userId);
           //Now I want to sort the notes array as per creation date using usort
           usort($notes, array($this,"cmp"));
        }
     function cmp($a, $b) {
       return strtotime($a->getCreationDate()) > strtotime($b->getCreationDate())? -1:1;
     }
}
+4
source share
1 answer

You can set the order in your call to the repository, and not after that like that ...

$notes = $repository->findBy(
    array('userid' => $userId),    // search criteria
    array('creationdate' => 'ASC') // order criteria
);

I know that you said you want to use usort, but that seems unnecessary.

+1
source

All Articles