note 97400 added to function.sort

From: Date: Sun, 18 Apr 2010 00:14:26 +0000
Subject: note 97400 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-168358@lists.php.net to get a copy of this message
In Response to Dollar Hauler Admin, this is a little rewrite of your function. <?php function multisort(array &$func_array, $func_sortKey) { $func_tmpArray = $func_retVal = array(); foreach($func_array as $func_index => $func_value) $func_tmpArray[$func_index] = $func_value[$func_sortKey]; asort($func_tmpArray); $func_args = func_get_args(); switch(func_num_args()) { case 2: $func_transfer = function(&$func_a, $func_b) { return $func_a = $func_b; }; break; default: $func_transfer = function(&$func_a, $func_b) use($func_args) { foreach($func_args as $func_index => $func_key) ($func_index) ? $func_a[$func_key] = $func_b[$func_key] : true; return $func_a; }; } foreach($func_tmpArray as $func_index => $func_value) $func_transfer($func_retVal[$func_index], $func_array[$func_index]); return $func_array = $func_retVal; } /* Usage: ====== array multisort(resource $array, mixed $sortBy[, $func_key[, $func_key2[, $func_key3 ... ]]]); Sorts the given $array by $sortBy of it Sub-Arrays. It only copies the given Keys (including $sortBy), but if none are given, all are copied. */ $array = array(array('name' => 'Chris', 'phone' => '3971095', 'year' => '1978', 'address' => 'Street 1'), array('name' => 'Breanne', 'phone' => '3766350', 'year' => '1990', 'address' => 'Street 2'), array('name' => 'Dusty', 'phone' => '1541120', 'year' => '1982', 'address' => 'Street 3')); $a = $b = $c = $array; // Example #1 // multisort($a, 'year'); //Copies all Keys from the Sub-Arrays and sorts by 'year' of the Sub-Arrays print_r($a); // Example #2 // $d = multisort($b, 'address', 'year'); //Copies only 'address' and 'year' from the Sub-Arrays and sorts by 'address' of the Sub-Arrays print_r($d); // Example #3 // print_r(multisort($c, 'phone', 'year', 'name', 'phone', 'phone')); //Copies 'phone', 'year' and 'name' from the Sub-Arrays and sorts by 'phone' of the Sub-Arrays ?> ---- Server IP: 69.147.83.197 Probable Submitter: 84.166.11.75 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/97400 Del: integrated -- https://master.php.net/note/delete/97400/integrated Del: useless -- https://master.php.net/note/delete/97400/useless Del: bad code -- https://master.php.net/note/delete/97400/bad+code Del: spam -- https://master.php.net/note/delete/97400/spam Del: non-english -- https://master.php.net/note/delete/97400/non-english Del: in docs -- https://master.php.net/note/delete/97400/in+docs Del: other reasons-- https://master.php.net/note/delete/97400 Reject -- https://master.php.net/note/reject/97400 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168358) next »