Home > Software design >  How can i sort a multi-dimensional array by it's keys in one of it's elements with usort i
How can i sort a multi-dimensional array by it's keys in one of it's elements with usort i

Time:06-01

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?

CodePudding user response:

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.

CodePudding user response:

If you want just to sort the 3rd element, you can sort it directly.

$array2 = [["15", "16", "17"], ["20", "25", "15"], ["1", "2", "1"]];
sort($array2[2]);

print_r($array2);

and will give you

Array
(
    [0] => Array
        (
            [0] => 15
            [1] => 16
            [2] => 17
        )

    [1] => Array
        (
            [0] => 20
            [1] => 25
            [2] => 15
        )

    [2] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 2
        )

)

Update

Inspired by vuryss's answer you can sort all subarrays via

$array2 = [["15", "16", "17"], ["20", "25", "15"], ["1", "2", "1"]];
array_walk($array2, fn(&$a) => sort($a));
  • Related