note 40652 added to function.usort

From: Date: Wed, 10 Mar 2004 18:40:18 +0000
Subject: note 40652 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-66575@lists.php.net to get a copy of this message
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 ) ) ---- Manual Page -- http://www.php.net/manual/en/function.usort.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40652 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40652&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40652&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#66575) next »