note 39857 added to function.sort
| From: | admin at lavacube dot net | Date: | Fri, 13 Feb 2004 03:17:26 +0000 |
| Subject: | note 39857 added to function.sort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-65076@lists.php.net to get a copy of this message | ||
I was looking for a method of sorting a multidimensional array by giving a key name, it will then
sort it by that key and keep everything else intact. The easiest way I found to accomplish this was
to have it jump through each key using the next(); function 'till it hit the right key, it
would then sort it by using a basic sort(); function. Example:
<?php
// +-- First let's set up the multidimensional array.
$array[0][username] = "user_name";
$array[0][password] = "pass_word";
$array[0][account_type] = "admin";
$array[1][username] = "eman_resu";
$array[1][password] = "drow_ssap";
$array[1][account_type] = "user";
$array[2][username] = "php_roxs";
$array[2][password] = "yesitdoes";
$array[2][account_type] = "admin";
// +-- Run it through the function.
$sorted = mu_sort($array, "account_type");
// +-- Print out the results[just for this test]
print_r($sorted);
// +-- Here's the function:
function mu_sort ($array, $key_sort) {
// first lets set the array pointer to the first key
reset($array);
// loop it through the keys
while(current($array)){
// if $key_sort is current: break.
if(key($array) == $key_sort){break;}
// if $key_sort is not current, jump to next key
next($array);
} // end loop
// return results after array
return($array);
} // end function
?>
//+-------------------
This will output:
//+-------------------
$array[0][password] = "drow_ssap";
$array[0][username] = "eman_resu";
$array[0][account_type] = "user";
$array[1][password] = "pass_word";
$array[1][username] = "user_name";
$array[1][account_type] = "admin";
$array[2][password] = "yesitdoes";
$array[2][username] = "php_roxs";
$array[2][account_type] = "admin";
[ This really comes in handy for small flat file DB's ]
----
Manual Page -- http://www.php.net/manual/en/function.sort.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+39857
Delete -- http://master.php.net/manage/user-notes.php?action=delete+39857&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+39857&report=yes
Search -- http://master.php.net/manage/user-notes.php