note 45346 added to function.natsort

From: Date: Thu, 02 Sep 2004 21:09:04 +0000
Subject: note 45346 added to function.natsort
Groups: php.notes 
Request: Send a blank email to php-notes+get-75959@lists.php.net to get a copy of this message
additional to the code posted by justin at redwiredesign dot com (which I found very usefull) here is a function that sorts complex arrays like this: <? $array['test0'] = array('main' => 'a', 'sub' => 'a'); $array['test2'] = array('main' => 'a', 'sub' => 'b'); $array['test3'] = array('main' => 'b', 'sub' => 'c'); $array['test1'] = array('main' => 'a', 'sub' => 'c'); $array['test4'] = array('main' => 'b', 'sub' => 'a'); $array['test5'] = array('main' => 'b', 'sub' => 'b'); ?> or <? $array[0] = array('main' => 1, 'sub' => 1); $array[2] = array('main' => 1, 'sub' => 2); $array[3] = array('main' => 2, 'sub' => 3); $array[1] = array('main' => 1, 'sub' => 3); $array[4] = array('main' => 2, 'sub' => 1); $array[5] = array('main' => 2, 'sub' => 2); ?> on one or more columns. the code <? $array = array_natsort_list($array,'main','sub'); ?> will result in $array being sortet like this: test0,test2,test1,test4,test5,test3 or 0,2,1,4,5,3. you may even submit more values to the function as it uses a variable parameter list. the function starts sorting on the last and the goes on until the first sorting column is reached. to me it was very usefull for sorting a menu having submenus and even sub-submenus. i hope it might help you too. here is the function: <? function array_natsort_list($array) { // for all arguments without the first starting at end of list for ($i=func_num_args();$i>1;$i--) { // get column to sort by $sort_by = func_get_arg($i-1); // clear arrays $new_array = array(); $temporary_array = array(); // walk through original array foreach($array as $original_key => $original_value) { // and save only values $temporary_array[] = $original_value[$sort_by]; } // sort array on values natsort($temporary_array); // delete double values $temporary_array = array_unique($temporary_array); // walk through temporary array foreach($temporary_array as $temporary_value) { // walk through original array foreach($array as $original_key => $original_value) { // and search for entries having the right value if($temporary_value == $original_value[$sort_by]) { // save in new array $new_array[$original_key] = $original_value; } } } // update original array $array = $new_array; } return $array; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.natsort.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+45346 Delete -- http://master.php.net/manage/user-notes.php?action=delete+45346&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+45346&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#75959) next »