note 39857 deleted from function.sort by tularis
| From: | tularis@php.net | Date: | Sun, 29 Aug 2004 10:25:18 +0000 |
| Subject: | note 39857 deleted from function.sort by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-75547@lists.php.net to get a copy of this message | ||
Note Submitter: admin at lavacube dot net
----
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 ]