I know i can easy sort a multi-dimensional array like this:
$array = [["15", "20", "1"], ["16", "25", "2"], ["17", "15", "1"]];
by using compare function and usort in php:
function cmp($a, $b)
{
return strcmp($a[2], $b[2]);
}
usort($array, "cmp");
But what if i have another array:
$array2 = [["15", "16", "17"], ["20", "25", "15"], ["1", "2", "1"]];
Now, as you can see, things to compare are in last element (array) of the multi-dimensional array. I want to finally have this after sorting:
$array2sorted = [["15", "17", "16"], ["20", "15", "25"], ["1", "1", "2"]];
How can i do it with usort?
>Solution :
You can use array_walk to apply a sorting function to each member of the array. Combined with the PHP 7.4 arrow functions this can look like this:
array_walk($array2, fn (&$subArray) => usort($subArray, /*your logic*/));
EDIT:
Now when I read the question more carefully, this might not work as you requested.
You can use array_multisort instead like this:
$array2 = [["15", "16", "17"], ["20", "25", "15"], ["1", "2", "1"]];
array_multisort($array2[2], ...$array2);
This sorts every item of the array in the way only the last sub-array is sorted.