note 89919 added to function.usort

From: Date: Sat, 28 Mar 2009 20:25:32 +0000
Subject: note 89919 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-152561@lists.php.net to get a copy of this message
If you need to use usort with a key in the calling method, I wrote this as a utility: <?php function usort_comparison($obj, $method, $key) { $usorter = &new Usort($obj, $method, $key); return array($usorter, "sort"); } class Usort { function __construct($obj, $method, $key) { $this->obj = $obj; $this->method = $method; $this->key = $key; } function sort($a, $b) { return call_user_func_array(array($this->obj, $this->method), array($a, $b, $this->key)); } } ?> <?php require_once("util/usort.php"); class Foo { $items = array(FooBar(13), FooBar(2)); public function sorter() { usort($this-items, usort_comparison("Foo", "_cmp", "item")); } public static function _cmp($a, $b, $key) { return strcasecmp($a->$key, $b->$key); } } class FooBar { public $item; function __construct($val) { $this->item = $val; } } ?> ~ simple example... but in the way I need to use it was the key was used in a switch statement to choose the different member of the object to compare against dynamically (as in, sort by x or y or z) ---- Server IP: 208.69.120.35 Probable Submitter: 66.245.32.31 ---- Manual Page -- http://www.php.net/manual/en/function.usort.php Edit -- https://master.php.net/note/edit/89919 Del: integrated -- https://master.php.net/note/delete/89919/integrated Del: useless -- https://master.php.net/note/delete/89919/useless Del: bad code -- https://master.php.net/note/delete/89919/bad+code Del: spam -- https://master.php.net/note/delete/89919/spam Del: non-english -- https://master.php.net/note/delete/89919/non-english Del: in docs -- https://master.php.net/note/delete/89919/in+docs Del: other reasons-- https://master.php.net/note/delete/89919 Reject -- https://master.php.net/note/reject/89919 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#152561) next »