note 13699 modified in function.usort by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 16:33:11 +0000 |
| Subject: | note 13699 modified in function.usort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176088@lists.php.net to get a copy of this message | ||
These functions will sort an array by more than one element. The elements to sort by is specified in
$sortArr. If you eg. want to sort by $destArr[]["sortBy2"][0] you add
'["sortBy2"][0]' to $sortArr. Use it as much as you want!! If you modify it,
please let me know...
<?php
//The functions
function compare($a, $b) {
return cmpRec(0, $a, $b);
}
function cmpRec($i, $a, $b) {
global $sortArr;
if($i == sizeof($sortArr)) {
return 0;
}
$avalue = '$avalue = $a'.$sortArr[$i].';';
$bvalue = '$bvalue = $b'.$sortArr[$i].';';
eval($avalue);
eval($bvalue);
if($avalue == $bvalue) {
return cmpRec($i+1, $a, $b);
} else {
return ($avalue > $bvalue) ? (1) : (-1);
}
}
//For testing the functions
$destArr = array( array( "sortBy1" => 2, "sortBy2" => array(
"Fish", "eat seafood" )), array( "sortBy1" => 1,
"sortBy2" => array( "Lions", "eat everything" )), array(
"sortBy1" => 1, "sortBy2" => array( "Bird", "eat
birdfood" )) );
$sortArr = array( '["sortBy1"]', '["sortBy2"][0]' );
print_r($destArr);
usort($destArr, "compare");
reset($destArr);
print_r($destArr);
?>
--was--
These functions will sort an array by more than one element. The elements to sort by is specified in
$sortArr. If you eg. want to sort by $destArr[]["sortBy2"][0] you add
'["sortBy2"][0]' to $sortArr. Use it as much as you want!! If you modify it,
please let me know...
//The functions
function compare($a, $b) {
return cmpRec(0, $a, $b);
}
function cmpRec($i, $a, $b) {
global $sortArr;
if($i == sizeof($sortArr)) {
return 0;
}
$avalue = '$avalue = $a'.$sortArr[$i].';';
$bvalue = '$bvalue = $b'.$sortArr[$i].';';
eval($avalue);
eval($bvalue);
if($avalue == $bvalue) {
return cmpRec($i+1, $a, $b);
} else {
return ($avalue > $bvalue) ? (1) : (-1);
}
}
//For testing the functions
$destArr = array( array( "sortBy1" => 2, "sortBy2" => array(
"Fish", "eat seafood" )), array( "sortBy1" => 1,
"sortBy2" => array( "Lions", "eat everything" )), array(
"sortBy1" => 1, "sortBy2" => array( "Bird", "eat
birdfood" )) );
$sortArr = array( '["sortBy1"]', '["sortBy2"][0]' );
print_r($destArr);
usort($destArr, "compare");
reset($destArr);
print_r($destArr);
http://php.net/manual/en/function.usort.php