0
$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

Thank you for your help.

Ralph
  • 2,065
  • 3
  • 15
  • 23

1 Answers1

3

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
        )

)
Federkun
  • 36,084
  • 8
  • 78
  • 90