note 105764 deleted from function.usort by crell
| From: | crell@php.net | Date: | Wed, 30 Mar 2022 22:23:09 +0000 |
| Subject: | note 105764 deleted from function.usort by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217824@lists.php.net to get a copy of this message | ||
Note Submitter: Gok6tm
----
this is a new multisort function for sorting on multiple subfield like it will be in sql :
'ORDER BY field1, field2'
number of sort field is undefined
<?php
$array[] = array('soc' => 3, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>5);
$array[] = array('soc' => 1, 'code'=>2);
$array[] = array('soc' => 3, 'code'=>2);
//usage
print_r(multiSort($array, 'soc', 'code'));
function multiSort() {
//get args of the function
$args = func_get_args();
$c = count($args);
if ($c < 2) {
return false;
}
//get the array to sort
$array = array_splice($args, 0, 1);
$array = $array[0];
//sort with an anoymous function using args
usort($array, function($a, $b) use($args) {
$i = 0;
$c = count($args);
$cmp = 0;
while($cmp == 0 && $i < $c)
{
$cmp = strcmp($a[ $args[ $i ] ], $b[ $args[ $i ] ]);
$i++;
}
return $cmp;
});
return $array;
}
?>
output:
Array
(
[0] => Array
(
[soc] => 1
[code] => 1
)
[1] => Array
(
[soc] => 1
[code] => 1
)
[2] => Array
(
[soc] => 1
[code] => 2
)
[3] => Array
(
[soc] => 2
[code] => 1
)
[4] => Array
(
[soc] => 2
[code] => 5
)
[5] => Array
(
[soc] => 3
[code] => 1
)
[6] => Array
(
[soc] => 3
[code] => 2
)
)