views:

25

answers:

3

I've got to sort a list of Reservations (they're coupled to an event 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?

A: 

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')
    )
));
Daniel Wright
Actually, I'm just doing this:$this->Event->id = $event_id;$eventinfo = $this->Event->read();
Forceflow
Well, using the code in my answer is equivalent to a `read` call, and has the added benefit of performing sorting operations at the database level.
Daniel Wright
A: 

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

Sam D
A: 

I would be normalising the surnames before storing them - either all lowercase, all UPPERCASE or all Capitalised.

Leo
This is probably what I'll end up doing. Thanks.
Forceflow