note 93194 modified in function.usort by danbrown
| From: | danbrown@php.net | Date: | Tue, 03 Nov 2009 15:52:16 +0000 |
| Subject: | note 93194 modified in function.usort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162361@lists.php.net to get a copy of this message | ||
An even better implementation of osort [than my original, posted on 24-AUG-09 (since deleted)],
allowing for multiple properties and directions. With php 5.3.0 sorting by properties of an object
becomes MUCH simpler. Note that this uses anonymous functions / closures. Might find reviewing the
php docs on that useful. Look below for examples for previous version of php.
<?php
function osort(&$array, $props)
{
if(!is_array($props))
$props = array($props => true);
usort($array, function($a, $b) use ($props) {
foreach($props as $prop => $ascending)
{
if($a->$prop != $b->$prop)
{
if($ascending)
return $a->$prop > $b->$prop ? 1 : -1;
else
return $b->$prop > $a->$prop ? 1 : -1;
}
}
return -1; //if all props equal
});
}
?>
Usage:
<?php
osort($items, array("Color" => true, "Size" => false));
//or
osort($items, "Color");
?>
--was--
An even better implementation of osort, allowing for multiple properties and directions:
function osort(&$array, $props)
{
if(!is_array($props))
$props = array($props => true);
usort($array, function($a, $b) use ($props) {
foreach($props as $prop => $ascending)
{
if($a->$prop != $b->$prop)
{
if($ascending)
return $a->$prop > $b->$prop ? 1 : -1;
else
return $b->$prop > $a->$prop ? 1 : -1;
}
}
return -1; //if all props equal
});
}
Usage:
osort($items, array("Color" => true, "Size" => false));
//or
osort($items, "Color");
http://php.net/manual/en/function.usort.php