note 97400 deleted from function.sort by danbrown
| From: | danbrown@php.net | Date: | Sun, 18 Apr 2010 02:42:20 +0000 |
| Subject: | note 97400 deleted from function.sort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168363@lists.php.net to get a copy of this message | ||
Note Submitter: Alex Rath
----
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
?>