CakePHP sort ignore case
I've got to sort a list of Reservations (they're coupled to an even开发者_如何转开发t by defining a belongsTo association) by the last name of the person who registered the ticket.
I do this in cakePHP:
$reservations = Set::sort($eventinfo['Reservation'],'{n}.last_name','asc');
This works, but some users input their data in all lowercase, which makes the sorting wrong:
Alfa, Ziggy, aardvark, zorro
Where it should be:
aardvark, Alfa, Ziggy, zorro
How can I fix this? I could loop over the array and make every string start with an uppercase letter using ucword(), but that looks a bit ugly. Isn't there an easy way to alter the sort algorithm so it ignores case?
I would be normalising the surnames before storing them - either all lowercase, all UPPERCASE or all Capitalised.
Is there a reason you're not performing the sorting in SQL?
I assume there's a find
operation shortly before you call Set::sort
, which I imagine looks something like:
$reservations = $this->Event->find('first',array(
'conditions' => array('Event.id' => $my_event_id),
'contain' => array('Reservation')
));
You can instruct Cake's ORM to sort the contained Reservations with the same syntax as a standard find
operation, like so:
$reservations = $this->Event->find('first',array(
'conditions' => array('Event.id' => $my_event_id),
'contain' => array(
'Reservation' => array('order'=>'Reservation.last_name')
)
));
It looks like in the code Set::sort is using array_multisort under the hood http://php.net/manual/en/function.array-multisort.php so it is not going to give you case insensitive sorting. You could look at the code for Set::sort and make your own subclass of Set that uses something like natcasesort http://www.php.net/manual/en/function.natcasesort.php or use mysql to do the sorting first, which by default in mysql would be case insensitive sorting
精彩评论