note 74461 deleted from function.sort by colder
| From: | colder@php.net | Date: | Thu, 12 Apr 2007 12:48:17 +0000 |
| Subject: | note 74461 deleted from function.sort by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-125334@lists.php.net to get a copy of this message | ||
Note Submitter: richard at happymango dot me dot uk
Reason: bad code
----
This is a function to sort any 2D array by a specified sub array key, either ascending or
descending.
It is useful for sorting query results from a database by a particular field after the query has
been returned
It recreates the array as a hash to use ksort() then back again
By default it will sort ascending but if you specify $reverse as true it will return the records
sorted descending
By default the array is re created as an indexed array but if you set $keep_key to true it maintain
the keys (useful for associative arrays)
<?php
//function record_sort(Mixed Array &$records, String $field [, [Boolean $reverse=false],
[Boolean $keep_key=false]])
function record_sort(&$records, $field, $reverse=false, $keep_key=false)
{
$hash = array();
foreach($records as $key => &$record)
{
$hash[$record[$field]][$key] = $record;
unset($records[$key]);
}
($reverse)? krsort($hash) : ksort($hash);
$records = array();
foreach($hash as $key => &$field)
{
foreach($field as $key2 => &$record)
{
($keep_key)? $records[$key2] = $record : $records []= $record;
unset($field[$key2]);
}
unset($hash[$key]);
}
unset($hash);
}
// Example below
$airports = array
(
array( "code" => "LHR", "name" => "Heathrow" ),
array( "code" => "LGW", "name" => "Gatwick" ),
);
printf("Before: <pre>%s</pre>", print_r($airports, true));
record_sort($airports, "name");
printf("After: <pre>%s</pre>", print_r($airports, true));
?>
Example Outputs:
Before: Array
(
[0] => Array ( [code] => LHR, [name] => Heathrow )
[1] => Array ( [code] => LGW, [name] => Gatwick )
)
After: Array
(
[0] => Array ( [code] => LGW, [name] => Gatwick )
[1] => Array ( [code] => LHR, [name] => Heathrow )
)