This code does not run properly, but it suggests what I am trying to do:
function sort_2d_by_index($a,$i) {
function cmp($x, $y) {
// Nested function, can't find $i
// (global $i defeats the purpose of passing an arg)
if ($x[$i] == $y[$i]) { return 0; }
return ($x[$i] < $y[$i]) ? -1 : 1;
}
usort($a,"cmp");
return $a;
}
There HAS to be a much better way to do this. I’ve been examining ksort(), multisort(), and all sorts of sorts until I’m sort of tired trying to sort it all out.
The situation is this: I’ve got a 2-d array…
array(
array(3,5,7),
array(2,6,8),
array(1,4,9)
);
…and I want to sort by a column index. Say, column [1], would give this result:
array(
array(1,4,9),
array(3,5,7),
array(2,6,8)
);
Does someone have a link (I’m sure this has been asked before), or could someone say “you need foosort, definitely”. Thanks very much.
In the documentation of
array_multisortit is mentioned that it can be used for this kind of thing.You can’t avoid creating an array that consists of only one column:
This sorts both arrays synchronously so that afterwards your whole array is sorted in the same order as the $sort_column array is.
As of PHP 5.3 you can use a closure (pass
$iinto the function) by defining yourcmpfunction like this: