note 100534 added to function.array-multisort
| From: | jimpoz at jimpoz dot com | Date: | Thu, 21 Oct 2010 21:26:26 +0000 |
| Subject: | note 100534 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-173351@lists.php.net to get a copy of this message | ||
I came up with an easy way to sort database-style results. This does what example 3 does, except it
takes care of creating those intermediate arrays for you before passing control on to
array_multisort().
<?php
function array_orderby()
{
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach ($data as $key => $row)
$tmp[$key] = $row[$field];
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
?>
The sorted array is now in the return value of the function instead of being passed by reference.
<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
// Pass the array, followed by the column names and sort flags
$sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
?>
----
Server IP: 192.41.42.26
Probable Submitter: 165.230.151.248
----
Manual Page -- http://www.php.net/manual/en/function.array-multisort.php
Edit -- https://master.php.net/note/edit/100534
Del: integrated -- https://master.php.net/note/delete/100534/integrated
Del: useless -- https://master.php.net/note/delete/100534/useless
Del: bad code -- https://master.php.net/note/delete/100534/bad+code
Del: spam -- https://master.php.net/note/delete/100534/spam
Del: non-english -- https://master.php.net/note/delete/100534/non-english
Del: in docs -- https://master.php.net/note/delete/100534/in+docs
Del: other reasons-- https://master.php.net/note/delete/100534
Reject -- https://master.php.net/note/reject/100534
Search -- https://master.php.net/manage/user-notes.php