note 16408 deleted from function.array-multisort by irc-html

From: Date: Sat, 19 Jan 2002 21:06:37 +0000
Subject: note 16408 deleted from function.array-multisort by irc-html
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-25469@lists.php.net to get a copy of this message
Here is two functions I threw together to perform a multicolumn sort (sql like!). To get arround limitations in uasort, I had to use a static variable. Feel free to send me any comments. //Some test data $tarr = array ( array( 'name' => "mike", 'age' => 29, 'eyes' => 'blue'), array( 'name' => "eileen", 'age' => 59, 'eyes' => 'blue'), array( 'name' => "joe", 'age' => 24, 'eyes' => 'brown'), array( 'name' => "dan", 'age' => 31, 'eyes' => 'brown'), array( 'name' => "brian", 'age' => 35, 'eyes' => 'brown'), array( 'name' => "don", 'age' => 50, 'eyes' => 'brown') ); //Compare function we call from asort function col_cmp ( $a, $b = null) { static $collist = array(); // When called without $b set, load the collist array if ($b == null) { $collist = $a; return; } // Loop Through sorted columns foreach ($collist as $key => $val) { // If we don't have a match we can finish up // otherwise continues through the loop if ($a[$key] != $b[$key]) { // Check a for assending order if ($val == 'a') return ($a[$key] < $b[$key]) ? -1 : 1; //any thing else desc order (I'm lazey) else return ($a[$key] > $b[$key]) ? -1 : 1; } } // if we are here than all columns matched return 0; } function column_sort (&$arr , $col_list) { // load the column list into col_cmp col_cmp($col_list); // sort preserving keys uasort ($arr, "col_cmp"); } // just call column_sort column_sort ($tarr, array ( 'eyes' => 'd', 'name' => 'a', 'age' => 'a',)); foreach ($tarr as $key => $val) { echo $key, " - "; echo $val['name'], " - "; echo $val['age'], " - "; echo $val['eyes'], "<br>"; }

« previous php.notes (#25469) next »