Search code examples
phparrayssortingmultidimensional-array

Sort a 2D array by values in a column


Here is my array, let's call it $arr

Array ( [0] => Array ( [post] => 159 [city] => Denver [country] => [state] => Colorado) 
        [1] => Array ( [post] => 165 [city] => Miami [country] => United States [state] => Florida ) 
        [2] => Array ( [post] => 172 [city] => East Rutherford [country] => United States [state] => New Jersey ) )

I would like to sort this array by the key "city" in ascending order so the array will be:

Array ( [0] => Array ( [post] => 159 [city] => Denver [country] => [state] => Colorado) 
        [2] => Array ( [post] => 172 [city] => East Rutherford [country] => United States [state] => New Jersey )
        [1] => Array ( [post] => 165 [city] => Miami [country] => United States [state] => Florida ) )

I then want to also sort the array by the state key values in ascending order so it will look like this:

Array ( [0] => Array ( [post] => 159 [city] => Denver [country] => [state] => Colorado)
        [1] => Array ( [post] => 165 [city] => Miami [country] => United States [state] => Florida
        [2] => Array ( [post] => 172 [city] => East Rutherford [country] => United States [state] => New Jersey ) )

Solution

  • Here is a solution that solves your problem:

    <?php
    
    $arr = array(
        array("posts"=>323, "city"=>"london"),
        array("posts"=>223, "city"=>"birmingham"),
        array("posts"=>255, "city"=>"norwich"),
        array("posts"=>13, "city"=>"manchester"),
        array("posts"=>23, "city"=>"liverpool"),
    );
    
    function cmp($a, $b) 
    {
            return ($a["posts"] >= $b["posts"]);
    }
    
    
    usort($arr, "cmp");
    
    print_r($arr);
    ?>