note 40652 deleted from function.usort by danbrown

From: Date: Sun, 23 Jan 2011 16:29:33 +0000
Subject: note 40652 deleted from function.usort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176077@lists.php.net to get a copy of this message
Note Submitter: robert at sargant dot com ---- This is an extension to Todor's function below - it will sort a multidimensional array by a primary key, secondary key and so on. It uses the same method of passing arguments as array_multisort, including sort order flags (but not sort type flags - arrays are sorted as case-insensitive strings.) <?php function array_alternate_multisort() { $arguments = func_get_args(); $arrays = $arguments[0]; for ($c = (count($arguments)-1); $c > 0; $c--) { if (in_array($arguments[$c], array(SORT_ASC , SORT_DESC))) { continue; } $compare = create_function('$a,$b','return strcasecmp($a["'.$arguments[$c].'"], $b["'.$arguments[$c].'"]);'); usort($arrays, $compare); if ($arguments[$c+1] == SORT_DESC) { $arrays = array_reverse($arrays); } } return $arrays ; } ?> To demonstrate: <?php $dir_contents[] = array("is_dir" => 0, "name" => "b.jpg"); $dir_contents[] = array("is_dir" => 1, "name" => "e"); $dir_contents[] = array("is_dir" => 1, "name" => "a"); $dir_contents[] = array("is_dir" => 0, "name" => "d.png"); $dir_contents[] = array("is_dir" => 0, "name" => "c.png"); $dir_sorted = array_alternate_multisort($dir_contents, "is_dir", SORT_DESC, "name", SORT_ASC); print_r($dir_sorted); ?> Produces the output: Array ( [0] => Array ( [is_dir] => 1 [name] => a ) [1] => Array ( [is_dir] => 1 [name] => e ) [2] => Array ( [is_dir] => 0 [name] => b.jpg ) [3] => Array ( [is_dir] => 0 [name] => c.png ) [4] => Array ( [is_dir] => 0 [name] => d.png ) )

« previous php.notes (#176077) next »