Search code examples
phparrayssortingmultidimensional-array

Sort rows of a 2d array by the numeric values in a column


So I am looking to sort the multi dimensional array below by "fk_page_id" ascending. Does anyone have any pointers. I think usort() is where I have to look but it seems like I cant find anyone with my specific array structure.

Array
    (

    [0] => Array

        (
            [title] => subpage of subpage!
            [id] => 5
            [long_title] =>
            [fk_page_id] => 4                                
        )

    [1] => Array
        (
            [title] => about us subpage
            [id] => 4
            [long_title] => 
            [fk_page_id] => 2
        )

    [2] => Array
        (
            [title] => about us
            [id] => 2
            [long_title] => 
            [fk_page_id] => 1
        )

)

Solution

  • if you're using PHP 5.3+:

    define(ASC,1);
    define(DESC,-1);
    
    function colsort($array,$col,$order=ASC) {
        usort(
            $array,
            function($a,$b) use($col,$order) {
                return strcmp($a[$col],$b[$col])*$order;
            }
        );
        return $array;
    }
    
    colsort($x,'fk_page_id');