note 102552 added to function.usort
[email protected] Mon, 21 Feb 2011 02:22:41 -0800
| Newsgroups | php.notes |
|---|---|
| Message-ID | <[email protected]> |
To sort a multidimensional array (such as is returned from database query) by the values in $array[foo][$key]
e.g.
<?php
/** Potential pitfall if there is already a key of '__________'
* in the subarrays. Not likely I hope!
* -------------------------------------------------------------
*/
function array_sort_by_subval(&$array, $key) {
foreach($array as &$v) {
$v['__________'] = $v[$key];
}
usort($array, 'sort_by_underscores');
foreach($array as &$v) {
unset($v['__________']);
}
}
function sort_by_underscores($a, $b) {
if($a['__________'] == $b['__________']) return 0;
if($a['__________'] < $b['__________']) return -1;
return 1;
}
$n = array(array('a' => 0, 'b' => 7, 'c' => 2),
array('a' => 4, 'b' => 1, 'c' => 3),
array('a' => 7, 'b' => 3, 'c' => 1));
array_sort_by_subval($n, 'b');
?>
The array $n will now be:
array(array('a' => 4, 'b' => 1, 'c' => 3),
array('a' => 7, 'b' => 3, 'c' => 1),
array('a' => 0, 'b' => 7, 'c' => 2))
----
Server IP: 69.147.83.197
Probable Submitter: 86.12.188.97 (proxied: 127.0.0.1)
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/102552
Del: integrated -- https://master.php.net/note/delete/102552/integrated
Del: useless -- https://master.php.net/note/delete/102552/useless
Del: bad code -- https://master.php.net/note/delete/102552/bad+code
Del: spam -- https://master.php.net/note/delete/102552/spam
Del: non-english -- https://master.php.net/note/delete/102552/non-english
Del: in docs -- https://master.php.net/note/delete/102552/in+docs
Del: other reasons-- https://master.php.net/note/delete/102552
Reject -- https://master.php.net/note/reject/102552
Search -- https://master.php.net/manage/user-notes.php