Zend - The PHP Company




Arrays

Add Code


aasort() sort Associative Arrays by one or more Keys.  

Type: code fragment
Added by: metanurb
Entered: 04/04/2001
Last modified: 01/11/2006
Rating: **** (9 votes)
Views: 9957
Function for sorting associative arrays by one or more keys. Similar to "ORDER BY" in an SQL query.


<?php
/*
I use it for sorting the rows of MYSQL_ASSOC-results without the need to
query the database again... it helps when you have slow querys whose result only needs to be sorted again.

First transfer the result into an array like this:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) $DB_Array[] = $row;

Syntax: aasort($assoc_array, array("+first_key", "-second_key", etc..));

Example: aasort($db_array, array("+ID", "-AGE", "+NAME"));
Where the "+" in front of the keys stands for "ASC" and "-" for "DESC".

This sorts the array first ascending by "ID", then descending by "AGE" and
finally ascending by "NAME".

Note: the function does no error handling... so make sure all keys exist in the
array and they have a + or - as the first character.
To keep the $DB_Array between pages use sessions.

To use the function with other arrays, they must have the following format:

$array[1] = array("key" => "value", "key" => "value", etc..);
$array[2] = array("key" => "value", "key" => "value", etc..);
$array[4] = array("key" => "value", "key" => "value", etc..);
etc.

*/


function aasort(&$array$args) {
    foreach(
$args as $arg) {
        
$order_field substr($arg1strlen($arg)); 
        foreach(
$array as $array_row) {
            
$sort_array[$order_field][] = $array_row[$order_field];
        }
        
$sort_rule .= '$sort_array['.$order_field.'], '.($arg[0] == "+" SORT_ASC SORT_DESC).',';
    }
    eval (
"array_multisort($sort_rule".' &$array);');
}
?>


Usage Example


aasort($your_array, array("+A", "-B", "+C"));



Rate This Script





Search



This Category All Categories