note 99419 added to function.sort
| From: | phpdotnet at m4tt dot co dot uk | Date: | Mon, 16 Aug 2010 14:03:56 +0000 |
| Subject: | note 99419 added to function.sort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171736@lists.php.net to get a copy of this message | ||
Simple function to sort an array by a specific key. Maintains index association.
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$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:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
/*
Array
(
[12345] => Array
(
[id] => 12345
[first_name] => Joe
[surname] => Bloggs
[age] => 23
[sex] => m
)
[12347] => Array
(
[id] => 12347
[first_name] => Amy
[surname] => Jones
[age] => 21
[sex] => f
)
[12346] => Array
(
[id] => 12346
[first_name] => Adam
[surname] => Smith
[age] => 18
[sex] => m
)
)
Array
(
[12345] => Array
(
[id] => 12345
[first_name] => Joe
[surname] => Bloggs
[age] => 23
[sex] => m
)
[12347] => Array
(
[id] => 12347
[first_name] => Amy
[surname] => Jones
[age] => 21
[sex] => f
)
[12346] => Array
(
[id] => 12346
[first_name] => Adam
[surname] => Smith
[age] => 18
[sex] => m
)
)
*/
?>
----
Server IP: 69.147.83.197
Probable Submitter: 213.131.191.153
----
Manual Page -- http://www.php.net/manual/en/function.sort.php
Edit -- https://master.php.net/note/edit/99419
Del: integrated -- https://master.php.net/note/delete/99419/integrated
Del: useless -- https://master.php.net/note/delete/99419/useless
Del: bad code -- https://master.php.net/note/delete/99419/bad+code
Del: spam -- https://master.php.net/note/delete/99419/spam
Del: non-english -- https://master.php.net/note/delete/99419/non-english
Del: in docs -- https://master.php.net/note/delete/99419/in+docs
Del: other reasons-- https://master.php.net/note/delete/99419
Reject -- https://master.php.net/note/reject/99419
Search -- https://master.php.net/manage/user-notes.php