Search code examples
phpsortingmultidimensional-array

Sort a 2d array by one of its columns


I have this array:

[fournisseurs_1331566668.csv] => Array
    (
        [name] => fournisseurs_1331566668.csv
        [date] => 1331566694
    )

[fournisseurs_1385460508.csv] => Array
    (
        [name] => fournisseurs_1385460508.csv
        [date] => 1385460517
    )

[fournisseurs_1334062493.csv] => Array
    (
        [name] => fournisseurs_1334062493.csv
        [date] => 1334062505
    )

I want to sort by the date (Descending order).

What function should I use? I tried with sort() and array_multisort(), but I'm not getting the desired result.


Solution

  • I made this function to sort every multidimensional array by one of his columns :

     function sortArrayBy($array , $column_name,$sort=SORT_DESC){
    
        foreach ($array as $key => $row) {
          $column[$key]  = $row[$column_name];
        }
    
        array_multisort($column, $sort, $array);
        return $array;
    
    }
    

    Call it like this :

    <?php sortArrayBy($yourArray,'date') ; ?>