note 104766 deleted from function.usort by danbrown

From: Date: Wed, 06 Jul 2011 13:26:08 +0000
Subject: note 104766 deleted from function.usort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181282@lists.php.net to get a copy of this message
Note Submitter: andreiduca ---- The class method presented in the post below is by far the easiest method to use. Here's a remake which allows you to sort the array ascending or descending in a more user-friendly manner: <?php class sortByKey { var $key; function __construct($key) { $this->key = $key; } // comparison function for ascending order function asc($a,$b) { $key = $this->key; if ($a[$key] == $b[$key]) return 0; return (($a[$key] > $b[$key]) ? 1 : -1); } // comparison function for descending order function desc($a,$b) { $key = $this->key; if ($a[$key] == $b[$key]) return 0; return (($a[$key] < $b[$key]) ? 1 : -1); } } // then just call (as an example) usort($products, array(new sortByKey("price"), "desc")); // to sort an array of products by price in descending order ?>

« previous php.notes (#181282) next »