note 15030 modified in function.usort by danbrown

From: Date: Sun, 23 Jan 2011 16:32:43 +0000
Subject: note 15030 modified in function.usort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176086@lists.php.net to get a copy of this message
This lets you sort an associative multi-dimensional array by multiple key/field names. Much similiar to the SQL clause ORDER BY. Enjoy. <?php function cmp ($a, $b) { // Populate this array with your values... // Below is the SQL equivalent of // select * from blah ORDER BY date desc, type asc, name asc $vals = array( 'date' => 'd', 'type' => 'a', 'name' => 'a' ); while(list($key, $val) = each($vals)) { if($val == "d") { if ($a["$key"] > $b["$key"]) { return -1; } if ($a["$key"] < $b["$key"]) { return 1; } } if($val == "a") { if ($a["$key"] < $b["$key"]) { return -1; } if($a["$key"] > $b["$key"]) { return 1; } } } } ?> --was-- This lets you sort an associative multi-dimensional array by multiple key/field names. Much similiar to the SQL clause ORDER BY. Enjoy. function cmp ($a, $b) { // Populate this array with your values... // Below is the SQL equivalent of // select * from blah ORDER BY date desc, type asc, name asc $vals = array( 'date' => 'd', 'type' => 'a', 'name' => 'a' ); while(list($key, $val) = each($vals)) { if($val == "d") { if ($a["$key"] > $b["$key"]) { return -1; } if ($a["$key"] < $b["$key"]) { return 1; } } if($val == "a") { if ($a["$key"] < $b["$key"]) { return -1; } if($a["$key"] > $b["$key"]) { return 1; } } } } http://php.net/manual/en/function.usort.php

« previous php.notes (#176086) next »