Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i sort a multi-dimensional array by it's keys in one of it's elements with usort in php?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading