note 74460 deleted from function.asort by colder
| From: | colder@php.net | Date: | Thu, 12 Apr 2007 12:48:20 +0000 |
| Subject: | note 74460 deleted from function.asort by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-125335@lists.php.net to get a copy of this message | ||
Note Submitter: richard at happymango dot me dot uk
Reason: bad code
----
This is an even better, memory friendly version of my record_sort() function. This time i made sure
that it will not forget any records with the same value for the sort field.
Please see the original post from below http://uk2.php.net/manual/en/function.asort.php#71318
It now sorts the array passed to it instead of returning a new array.
Also you can now specify if you want to preserve the keys of the array which is useful if you pass
it an associative array of records rather than an indexed.
<?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);
}
?>