phparrayssortingmultidimensional-array

Sorting a 2d array by one column then another column


$student_data = array(
    array(
        "id" => 1,
        "student_name" => "Kasimir Clark",
        "country" => "Chile"
    ),
    array(
        "id" => 2,
        "student_name" => "Kyle Myers",
        "country" => "Cook Islands"
    ),
    array(
        "id" => 3,
        "student_name" => "Merrill Velez",
        "country" => "Israel"
    ),
    array(
        "id" => 4,
        "student_name" => "Kadeem Graham",
        "country" => "Christmas Island"
    ),
);

usort($student_data, function($a, $b)
{
    return $a["student_name"] - $b["student_name"];
});

I need to sort the multi-dimentional array in PHP. Is it possible to sort the country then by the name? I tried to achieve in usort but I can only sort by one condition such as either name or country.

I would like to achieve something like what MySQL database is doing. Something like

SELECT * FROM STUDENT order by country,name


Solution

  • Use array_multisort, I found an implementation in the comments.

    function array_orderby()
    {
        $args = func_get_args();
        $data = array_shift($args);
        foreach ($args as $n => $field) {
            if (is_string($field)) {
                $tmp = array();
                foreach ($data as $key => $row)
                    $tmp[$key] = $row[$field];
                $args[$n] = $tmp;
                }
        }
        $args[] = &$data;
        call_user_func_array('array_multisort', $args);
        return array_pop($args);
    }
    
    $student_data = array(
        array(
            "id" => 1,
            "student_name" => "Kasimir Clark",
            "country" => "Chile"
        ),
        array(
            "id" => 2,
            "student_name" => "Kyle Myers",
            "country" => "Cook Islands"
        ),
        array(
            "id" => 3,
            "student_name" => "Merrill Velez",
            "country" => "Israel"
        ),
        array(
            "id" => 4,
            "student_name" => "Kadeem Graham",
            "country" => "Christmas Island"
        )
    );
    
    
    $sorted = array_orderby($student_data, 'country', SORT_ASC, 'student_name', SORT_ASC);
    
    print_r($sorted);
    

    This print:

    Array
    (
        [0] => Array
            (
                [id] => 1
                [student_name] => Kasimir Clark
                [country] => Chile
            )
    
        [1] => Array
            (
                [id] => 4
                [student_name] => Kadeem Graham
                [country] => Christmas Island
            )
    
        [2] => Array
            (
                [id] => 2
                [student_name] => Kyle Myers
                [country] => Cook Islands
            )
    
        [3] => Array
            (
                [id] => 3
                [student_name] => Merrill Velez
                [country] => Israel
            )
    
    )