Search code examples
phparrayssortingmultidimensional-array

How to sort a 2-d array by a column?


I have a multidimensional array in php and I want to sort it according to the entered time.

Array
(
    [0] => Array
        (
            [account_id] => 9
            [entered] => 1369374812
        )

    [1] => Array
        (
            [account_id] => 9
            [entered] => 1377587453
        )

    [2] => Array
        (
            [account_id] => 9
            [entered] => 1373542381
        )

    [3] => Array
        (
            [account_id] => 9
            [entered] => 1372988725
        )

    [4] => Array
        (
            [account_id] => 353
            [entered] => 1380191316
        )

    [5] => Array
        (
            [account_id] => 9
            [entered] => 1377587610
        )
)

Solution

  • Try this,

    function aasort (&$array, $key) {
        $sorter=array();
        $ret=array();
        reset($array);
        foreach ($array as $ii => $va) {
            $sorter[$ii]=$va[$key];
        }
        asort($sorter);
        foreach ($sorter as $ii => $va) {
            $ret[$ii]=$array[$ii];
        }
        $array=$ret;
    }
    
    aasort($your_array,"account_id");