note 96019 added to function.natsort
| From: | the_A at gmx dot at | Date: | Wed, 03 Feb 2010 15:55:54 +0000 |
| Subject: | note 96019 added to function.natsort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-165626@lists.php.net to get a copy of this message | ||
Another approach to a natsord2d-function:
Imagine having an array like:
Array
(
[subarray1] => Array
(
[1] => foo
[2] => bar
)
[subarray2] => Array
(
[1] => 12
[2] => 2
)
)
and you want to natsort it (=all the sub-arrays) by the values of sub-array2
<?php
function natsort2d_custom (&$array, $sortby) {
natsort($array[$sortby]); //First natsort the specified sub-array $sortby
$sorted_array = array(); //Create a temporary array
$sorted_array[$sortby] = $array[$sortby]; //Add the sorted sub-array to the temporary array with
teh same key
foreach($array AS $key1=>$value1) { //Walking through the rest of $array, ...
if($key1 != $sortby) { //...leaving out [$sortby]
$sorted_array[$key1] = array(); //Create sub-array $key1
foreach ($array[$sortby] AS $key2=>$value2) { //Walk trough $array[$sortby] (which is now
already natsorted) key by key
$sorted_array[$key1][$key2] = $array[$key1][$key2];
// Put keys (and values) of array[$key1] in the same order as array[$sort] and stuff it into
$sorted_array with the same key
}
}
}
$array = $sorted_array;
reset($array);
}
?>
After sorting the array this way, it would be:
Array
(
[subarray1] => Array
(
[2] => bar
[1] => foo
)
[subarray2] => Array
(
[2] => 2
[1] => 12
)
)
This works, of course, with an unlimited amount of sub-arrays, provided none of the sub-arrays has a
sub-array itself (non-recoursive)
----
Server IP: 69.147.83.197
Probable Submitter: 85.125.61.162
----
Manual Page -- http://www.php.net/manual/en/function.natsort.php
Edit -- https://master.php.net/note/edit/96019
Del: integrated -- https://master.php.net/note/delete/96019/integrated
Del: useless -- https://master.php.net/note/delete/96019/useless
Del: bad code -- https://master.php.net/note/delete/96019/bad+code
Del: spam -- https://master.php.net/note/delete/96019/spam
Del: non-english -- https://master.php.net/note/delete/96019/non-english
Del: in docs -- https://master.php.net/note/delete/96019/in+docs
Del: other reasons-- https://master.php.net/note/delete/96019
Reject -- https://master.php.net/note/reject/96019
Search -- https://master.php.net/manage/user-notes.php