Search code examples
phparrayssortingmultidimensional-array

Sort a 2d array by a column's values


I have an array fetched from mysql database tables of type. I want to sort it in order of particular value.

$arr1 = array(
    array(12, 8, 5, 34),
    array(54, 87, 32, 10),
    array(23, 76, 98, 13),
    array(53, 16, 24, 19)
);

How can I sort it by value? Like sorting by 2nd value should result to.

$arr1 = array(
    array(12, 8, 5, 34),
    array(53, 16, 24, 19),
    array(23, 76, 98, 13),
    array(54, 87, 32, 10)
);

Solution

  • I like to use usort to solve these problems.

    $sortKey = 1;
    usort($arr1, function($a, $b) use($sortKey){
        return $a[$sortKey] - $b[$sortKey];
    });