note 13699 deleted from function.usort by cmb

From: Date: Sun, 22 Sep 2019 07:53:51 +0000
Subject: note 13699 deleted from function.usort by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212288@lists.php.net to get a copy of this message
Note Submitter: johan_land at yahoo dot com ---- 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); ?>

« previous php.notes (#212288) next »