note 36774 added to function.uasort

From: Date: Wed, 22 Oct 2003 03:57:09 +0000
Subject: note 36774 added to function.uasort
Groups: php.notes 
Request: Send a blank email to php-notes+get-59090@lists.php.net to get a copy of this message
Hope this helps! - Remmy <?php // Based on the other notes given before. // Sorts an array (you know the kind) by key // and by the comparison operator you prefer. // Note that instead of most important criteron first, it's // least important criterion first. // The default sort order is ascending, and the default sort // type is strnatcmp. // function multisort($array[, $key, $order, $type]...) function multisort($array) { for($i = 1; $i < func_num_args(); $i += 3) { $key = func_get_arg($i); $order = true; if($i + 1 < func_num_args()) $order = func_get_arg($i + 1); $type = 0; if($i + 2 < func_num_args()) $type = func_get_arg($i + 2); switch($type) { case 1: // Case insensitive natural. $t = 'strcasenatcmp($a[' . $key . '], $b[' . $key . '])'; break; case 2: // Numeric. $t = '$a[' . $key . '] - $b[' . $key . ']'; break; case 3: // Case sensitive string. $t = 'strcmp($a[' . $key . '], $b[' . $key . '])'; break; case 4: // Case insensitive string. $t = 'strcasecmp($a[' . $key . '], $b[' . $key . '])'; break; default: // Case sensitive natural. $t = 'strnatcmp($a[' . $key . '], $b[' . $key . '])'; break; } uasort($array, create_function('$a, $b', 'return ' . ($order ? '' : '-') . '(' . $t . ');')); } return $array; } $a = array( array('id' => 1, 'name' => 'apple'), array('id' => 2, 'name' => 'orange'), array('id' => 8, 'name' => 'banana'), array('id' => 8, 'name' => 'grapefruit'), array('id' => 9, 'name' => 'smoke'), array('id' => 1, 'name' => 'screen') ); // This works like MYSQL 'ORDER BY id DESC, name ASC' // Note the quoting of string literal keys. echo('<pre>'); print_r(multisort($a, "'name'", true, 0, "'id'", false, 2)); echo('</pre>'); ?> ---- Manual Page -- http://www.php.net/manual/en/function.uasort.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+36774 Delete -- http://master.php.net/manage/user-notes.php?action=delete+36774&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+36774&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#59090) next »