Re: sort array of objects by muliple values [message #172029 is a reply to message #172027] |
Thu, 27 January 2011 21:38 |
Max
Messages: 4 Registered: January 2011
Karma:
|
Junior Member |
|
|
On Jan 27, 10:27 pm, Denis McMahon <denis.m.f.mcma...@googlemail.com>
wrote:
> On 27/01/11 19:59, 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
>
> The thing with a user defined sort is that you have to write the sort
> function yourself, and it can sort on whatever you want it to:
>
> <?php
>
> class User {
> private $firstname;
> private $surname;
> private $birthday;
>
> function __construct($firstname, $surname, $birthday) {
> $this->firstname = $firstname;
> $this->surname = $surname;
> $this->birthday = $birthday;
> }
> function __get($n) {
> return $this->$n;
> }
>
> }
>
> function cmp_User($a, $b)
> {
> if ($a->birthday == $b->birthday) {
> if ($a->surname == $b->surname) {
> return 0;
> }
> return ($a->surname < $b->surname) ? -1 : 1;
> }
> return ($a->birthday < $b->birthday) ? -1 : 1;
>
> }
>
> $a = array (
> new User('Alice', 'Smith', '1960-01-01'),
> new User('Michael', 'Jordan', '1950-01-01'),
> new User('Kevin', 'Dilan', '1950-01-01'),
> );
>
> print "Before Sort\n===========\n";
>
> foreach ($a as $key => $value) {
> print "Item $key; Name: {$value->surname}, {$value->firstname}; DOB:
> {$value->birthday}\n";
>
> }
>
> usort($a, "cmp_User");
>
> print "\nAfter Sort\n==========\n";
>
> foreach ($a as $key => $value) {
> print "Item $key; Name: {$value->surname}, {$value->firstname}; DOB:
> {$value->birthday}\n";
>
> }
>
> ?>
>
> generates:
>
> Before Sort
> ===========
> Item 0; Name: Smith, Alice; DOB: 1960-01-01
> Item 1; Name: Jordan, Michael; DOB: 1950-01-01
> Item 2; Name: Dilan, Kevin; DOB: 1950-01-01
>
> After Sort
> ==========
> Item 0; Name: Dilan, Kevin; DOB: 1950-01-01
> Item 1; Name: Jordan, Michael; DOB: 1950-01-01
> Item 2; Name: Smith, Alice; DOB: 1960-01-01
>
> Rgds
>
> Denis McMahon
Thanks for example! What if sort direction and/or fields only known at
runtime?
|
|
|