note 93194 deleted from function.usort by crell

From: Date: Wed, 30 Mar 2022 22:24:49 +0000
Subject: note 93194 deleted from function.usort by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-217828@lists.php.net to get a copy of this message
Note Submitter: Will Shaver ---- 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"); ?>

« previous php.notes (#217828) next »