FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » sort array of objects by muliple values
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: sort array of objects by muliple values [message #172028 is a reply to message #172024] Thu, 27 January 2011 21:31 Go to previous messageGo to previous message
Denis McMahon is currently offline  Denis McMahon
Messages: 634
Registered: September 2010
Karma:
Senior Member
On 27/01/11 20:46, Peter H. Coffin wrote:
> On Thu, 27 Jan 2011 11:59:28 -0800 (PST), Max wrote:
>> On Jan 27, 8:10?pm, Jerry Stuckle <jstuck...@attglobal.net> wrote:
>>> On 1/27/2011 2:04 PM, Max wrote:
>>>
>>>> Is there a simple way to sort $array below like SQL it does? I.e.
>>>> ORDER BY birthday ASC, name ASC
>>>> Output would be Kevin, Michael, Alice
>>>
>>>> Thanks!
>>>
>>>> <?php
>>>> class User {
>>>> ? ? ?private $firstname;
>>>> ? ? ?private $surname;
>>>> ? ? ?private $birthday;
>>>
>>>> ? ? ?function __construct($firstname, $surname, $birthday) {
>>>> ? ? ? ? ?$this->firstname = $name;
>>>> ? ? ? ? ?$this->surname = $surname;
>>>> ? ? ? ? ?$this->birthday = $birthday;
>>>> ? ? ?}
>>>> ? ? ?function __get($n) {
>>>> ? ? ? ? ?return $this->$n;
>>>> ? ? ?}
>>>> }
>>>
>>>> $array = array (
>>>> ? ? ? ? ?new User('Alice', ? ? ? 'Smith', ?'1960-01-01'),
>>>> ? ? ? ? ?new User('Michael', ? 'Jordan', ?'1950-01-01'),
>>>> ? ? ? ? ?new User('Kevin', ? ? ?'Dilan', ? ?'1950-01-01'),
>>>> ? ? ? ? ?);
>>>
>>> Use usort() with a static member function. ?See
>>>
>>> http://us2.php.net/manual/en/function.usort.php
>>>
>>> for an example.
>>
>> it sorts only by one field
>
> If you sort a sorted array by another column, what do you think happens
> to the records in identically-keyed records?

It's not an array of columns, it's an array of records (or objects
defined by the class constructor), and what he needs is a compare
function callback for usort that's aware of the class structure and the
properties he wants to sort by.

Pretty trivial exercise really.

Rgds

Denis McMahon
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: SNMPv3 for PHP?
Next Topic: Using server to list CSS page list in menu
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Mon Feb 17 05:06:44 GMT 2025

Total time taken to generate the page: 0.04466 seconds