note 99700 modified in function.sort by danbrown
| From: | danbrown@php.net | Date: | Tue, 31 Aug 2010 14:51:22 +0000 |
| Subject: | note 99700 modified in function.sort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-172198@lists.php.net to get a copy of this message | ||
The code below will sort via a field passed as the $on parameter, 3rd parameter is
'SORT_DESC' or 'SORT_ASC'. The function from the previous developer below mine
maintains the array index value good for associative arrays but for normal arrays with associative
fields like database queries returned as arrays use this.
<?php
function array_sort($array, $on, $order='SORT_DESC')
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch($order)
{
case 'SORT_ASC':
echo "ASC";
asort($sortable_array);
break;
case 'SORT_DESC':
echo "DESC";
arsort($sortable_array);
break;
}
foreach($sortable_array as $k => $v) {
$new_array[] = $array[$k];
}
}
return $new_array;
}
?>
--was--
The code below will sort via a field passed as the $on parameter, 3rd parameter is
'SORT_DESC' or 'SORT_ASC'. The function from the previous developer below mine
maintains the array index value good for associative arrays but for normal arrays with associative
fields like database queries returned as arrays use this.
function array_sort($array, $on, $order='SORT_DESC')
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch($order)
{
case 'SORT_ASC':
echo "ASC";
asort($sortable_array);
break;
case 'SORT_DESC':
echo "DESC";
arsort($sortable_array);
break;
}
foreach($sortable_array as $k => $v) {
$new_array[] = $array[$k];
}
}
return $new_array;
}
http://php.net/manual/en/function.sort.php