note 93986 added to function.uasort

From: Date: Sat, 10 Oct 2009 03:34:25 +0000
Subject: note 93986 added to function.uasort
Groups: php.notes 
Request: Send a blank email to php-notes+get-161613@lists.php.net to get a copy of this message
I couldn't work out a way to specify what element to sort by using the existing php functions - maybe I didn't look hard enough?? So i wrote my own multidimensional array sorting class. <?php $stock = array(array("id" => 1,"item" => "hat", "number" => 5, "price" => 15), array("id" => 5,"item" => "shoes", "number" => 1, "price" => 50), array("id" => 3,"item" => "tie", "number" => 2, "price" => 30)); $sort = new multiSort(); //will sort the array by id in ascending order print_r ($sort->sortArray($stock,'id','rcmp')); //will sort the array by id in descending order print_r ($sort->sortArray($stock,'id','cmp')); //can also be used like so (specifying the index of the array) print_r ($sort->sortArray($stock,'0','rcmp')); ////////////////////////////////////////////////////// class multiSort { function sortArray($array,$parameter,$_function) { return $this->_uasort($array,$_function,$parameter); } function cmp ($a, $b, $p) { return (strcmp ($a[$p],$b[$p]));} function rcmp ($a, $b, $p) { return -1 * (strcmp ($a[$p],$b[$p]));} function _uasort($array,$func,$param) { for($i=0;$i<sizeof($array);$i++) { $tmp = $i; for($j=1;$j<sizeof($array);$j++) { $result = $this->$func($array[$tmp],$array[$j],$param); if($result == -1) { $array = $this->arraySwap($array,$tmp,$j); $tmp = $j; } } } return $array; } function arrayswap($arr, $src, $dst) { $tmp = $arr[$dst]; $arr[$dst] = $arr[$src]; $arr[$src] = $tmp; return $arr; } } ////////////////////////////////////////////////////////// ?> hope someone finds this useful. ---- Server IP: 69.147.83.197 Probable Submitter: 120.17.187.105 ---- Manual Page -- http://www.php.net/manual/en/function.uasort.php Edit -- https://master.php.net/note/edit/93986 Del: integrated -- https://master.php.net/note/delete/93986/integrated Del: useless -- https://master.php.net/note/delete/93986/useless Del: bad code -- https://master.php.net/note/delete/93986/bad+code Del: spam -- https://master.php.net/note/delete/93986/spam Del: non-english -- https://master.php.net/note/delete/93986/non-english Del: in docs -- https://master.php.net/note/delete/93986/in+docs Del: other reasons-- https://master.php.net/note/delete/93986 Reject -- https://master.php.net/note/reject/93986 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#161613) next »