note 36711 added to function.array-multisort
| From: | siivv at siivv dot com | Date: | Mon, 20 Oct 2003 02:23:27 +0000 |
| Subject: | note 36711 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-58907@lists.php.net to get a copy of this message | ||
this post expounds on that by adriano_allora at mac dot com
say u have an array like this:
$array = array("page1" => array("hits" => 1, "bytes" => 2),
"page2" => array("hits" => 2, "bytes" => 30))
and say u want to sort it based on hits, so that you can see which page had the most hits
normally this could be accomplished with uksort and a compare function, but since wrapping a compare
function into a class is a problem in itself... i came up with this function, that can used as a
method within the class:
function matrixSort($matrix,$sortKey) {
foreach ($this->{$matrix} as $key => $subMatrix)
$tmpArray[$key] = $subMatrix[$sortKey];
arsort($tmpArray);
$this->{$matrix} = array_merge($tmpArray,$this->{$matrix});
}
(and a version not necessarily wrapped into a class)
function matrixSort(&$matrix,$sortKey) {
foreach ($matrix as $key => $subMatrix)
$tmpArray[$key] = $subMatrix[$sortKey];
arsort($tmpArray);
return array_merge($tmpArray,$matrix);
}
this returns the same matrix form as above, but with the key "page2" now as the first
element based on the sort
this solved the simple problem i was having which dissallowed me from making this process reusable
within a class framework. without this i would have had to create a function, by itself, outside my
class... which i considered very clunky coding
----
Manual Page -- http://www.php.net/manual/en/function.array-multisort.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+36711
Delete -- http://master.php.net/manage/user-notes.php?action=delete+36711&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+36711&report=yes
Search -- http://master.php.net/manage/user-notes.php