sort
and its cousins have variations where you can supply your own sorting callback function: usort
, uasort
(which maintains indexes), and uksort
(which sorts on the keys. You'll have to create your own sorting callback to do what you want to do here.
function sort_by_subarray($a, $b)
{
// $a and $b are elements of $array that are being compared against
// each other to be sorted
if (!isset($a[1]) || !isset($b[1]))
{
// Do something if $a[1] or $b[1] is undefined
// Your question doesn't define what the behaviour here should be
}
else
{
if ($a[1] == $b[1]) return 0; // the elements are the same
return ($a[1] < $b[1]) ? -1 : 1; // otherwise, sort from lowest to highest
}
}
$array = array(
array(1, 8, 2),
array(5, 6, 15),
array(-8, 2, 1025)
);
uasort($array, "sort_by_subarray");
/* Results in:
Array
(
[2] => Array
(
[0] => -8
[1] => 2
[2] => 1025
)
[1] => Array
(
[0] => 5
[1] => 6
[2] => 15
)
[0] => Array
(
[0] => 1
[1] => 8
[2] => 2
)
)
*/
Note that my function will sort two subarrays as being equal if $subarray[1] is equal, so if you want to be more specific, you can add more rules for when $a[1] == $b[1]
.