"We are back" « oc.at

Mehrdimensionales Array sortieren ?

bBU.CyTrobIc 09.03.2004 - 15:54 531 2
Posts

bBU.CyTrobIc

#include "billrulz.h"
Avatar
Registered: Oct 2000
Location: Hamburg
Posts: 1875
Moin,

ich hab mal wieder ne Frage,

Mein Beispielarray schaut so aus:

Code:
$a = array(
   array('a' => 1, 'b' => 1, 'c' => 1, 'd' => 3),
   array('a' => 3, 'b' => 4, 'c' => 4, 'd' => 1),
   array('a' => 4, 'b' => 3, 'c' => 2, 'd' => 4),
   array('a' => 2, 'b' => 2, 'c' => 3, 'd' => 2)
);

Ich möchte jetzt das das array komplett absteigend nach
dem 'd' sortiert wird. Das soll nach dem Sortieren dann
wie folgt aussehen:

Code:
$a = array(
   array('a' => 4, 'b' => 3, 'c' => 2, 'd' => 4),
   array('a' => 1, 'b' => 1, 'c' => 1, 'd' => 3),
   array('a' => 2, 'b' => 2, 'c' => 3, 'd' => 2),
   array('a' => 3, 'b' => 4, 'c' => 4, 'd' => 1)
);

Also es sollen die array in dem multiarray nach 'd'
gelistet werden. Wie stell ich das an ?

Thx Gerrit

watchout

Legend
undead
Avatar
Registered: Nov 2000
Location: Off the grid.
Posts: 6845
Vielleicht hilft dir folgender Text von php.net:
(http://at.php.net/manual/en/functio...y-multisort.php)
Zitat
siivv at siivv dot com
20-Oct-2003 04:23
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

bBU.CyTrobIc

#include "billrulz.h"
Avatar
Registered: Oct 2000
Location: Hamburg
Posts: 1875
ich probiers mal aus
Kontakt | Unser Forum | Über overclockers.at | Impressum | Datenschutz