Entry
Can I sort a 3 dimensional array in PHP?
Aug 4th, 2000 15:36
Walter Flaschka, Nathan Wallace, http://px.sklar.com/code-pretty.html?code_id=21
Sort it how?...
You may need to iterate through the first dimension and sort each
sub-array, or perhaps you could write a custom comparison
function for
usort() that will evaluate and sort the sub-array...
There's no real way to answer this question unless you explain
which
dimension you want to sort, and what to do with the other two
dimensions.
----------------------------------------------------
ANSWER:
There is some discussion on this at:
http://www.php.net/manual/function.usort.php
Note the comment by: justin@internetpartners.com
This code works:
##init array somehow
$myarray[] = array("val1.1", "val2.1", "d", "val4.1", "valn.1");
$myarray[] = array("val1.2", "val2.2", "c", "val4.2", "valn.2");
$myarray[] = array("val1.3", "val2.3", "b", "val4.3", "valn.3");
$myarray[] = array("val1.4", "val2.4", "a", "val4.4", "valn.4");
##show pre-sorted values
print "<PRE>pre-sorted:\n";
for ($i=0; $i<count($myarray); $i++) {
print implode(" ", $myarray[$i])."\n";
}
print "</PRE>\n";
print "<BR> <BR>\n";
##create a function to compare
function do_my_sort($a, $b) {
#note that we're comparing the 3rd element
return strcmp($a[2], $b[2]);
}
##do the actual sorting work
usort($myarray, do_my_sort);
##show values after sorting
print "<PRE>Post-sort:\n";
for ($i=0; $i<count($myarray); $i++) {
print implode(" ", $myarray[$i])."\n";
}
print "</PRE>\n";