note 43914 added to function.uksort
| From: | fabriceb at gmx dot net | Date: | Thu, 08 Jul 2004 10:26:23 +0000 |
| Subject: | note 43914 added to function.uksort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-72875@lists.php.net to get a copy of this message | ||
(about sorting an array of objects by their properties in a class - inspired by webmaster at zeroweb
dot org at usort function)
I'm using classes as an abstraction for querying records in a database and use arrays of
objects to store records that have an 1 to n relationship. E.g. a class "family" has
family members stored as an array of objects. Each of those objects prepresents a record in a
database related to the family (by it's familyId).
To identify members, I'm using their memberId as the key of the array e.g.
$family->members[$memberId].
To sort the family members AFTER fetching them with the database query, you can use the functions
_objSort and sortMembers which will sort the "members" array by key using it's
properties (for space reasons I didn't include the methods used to open the records):
<?php
class familyMember
{
var $memberId;
var $familyId;
var $firstName;
var $age;
var $hairColor;
// ...
}
class family
{
var $familyId;
var $name;
var $members = array(); // array of familyMember objects
var $sortFields = array();
var $sortDirections = array();
// ...
function _objSort(&$a, &$b, $i = 0)
{
$field = $this->sortFields[$i];
$direction = $this->sortDirections[$i];
$diff = strnatcmp($this->details[$a]->$field, $this->details[$b]->$field) *
$direction;
if ($diff == 0 && isset($this->sortFields[++$i]))
{
$diff = $this->_objSort($a, $b, $i);
}
return $diff;
}
function sortMembers($sortFields)
{
$i = 0;
foreach ($sortFields as $field => $direction)
{
$this->sortFields[$i] = $field;
$direction == "DESC" ? $this->sortDirections[$i] = -1 : $this->sortDirections[$i]
= 1;
$i++;
}
uksort($this->details, array($this, "_objSort"));
$this->sortFields = array();
$this->sortDirections = array();
}
}
// open a family
$familyId = 5;
$family = new family($familyId);
$family->open(); // this will also fetch all members
// sort members by 3 fields
$family->sortMembers(array("firstName" => "ASC", "age" =>
"DESC", "hairColor" => "ASC"));
// output all family members
foreach ($family->members as $member)
{
echo $member->firstName." - ".$member->age." -
".$member->hairColor."<br />";
}
?>
Note that this might not be the fastest thing on earth and it hasn't been tested very much yet
but I hope it's useful for someone.
----
Manual Page -- http://www.php.net/manual/en/function.uksort.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+43914
Delete -- http://master.php.net/manage/user-notes.php?action=delete+43914&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+43914&report=yes
Search -- http://master.php.net/manage/user-notes.php