Wednesday, 29 August 2018

The best way to sort a multidimensional array in PHP

I have this array :

$order_list = array ( array ("081", "01203", "2", "12000"),
                      array ("002", "01204", "8", NULL),
                      array ("021", "01207", "8", NULL),
                      array ("081", "01206", "8", NULL),
                      array ("043", "01205", "10", "14000"));

and I want to sort (ascending) that array based on the first value (081, 002, 021, 081 and 043). so it will look like this :
array ( array ("002", "01204", "8", NULL),
        array ("021", "01207", "8", NULL),
        array ("043", "01205", "10", "14000"),
        array ("081", "01203", "2", "12000"),
        array ("081", "01206", "8", NULL));

how to do that? I learned about asort() and ksort(), but it seems that only works for associative array, not multidimensional array.

You can use usort()
usort($yourArray, function ($a, $b) {
    if ($a[0] == $b[0]) return 0;
    return (int) $a[0] < (int) $b[0] ? -1 : 1;
});

The parameters $a and $b are your (sub)arrays. This simple function compares the first value in each of those.
If you had other than numbers in your array you could have used strcmp():
usort($yourArray, function ($a, $b) {
    return strcmp($a[0], $b[0]);
});

0 comments:

Post a Comment