php中的多维数组排序

时间:2015-10-13 23:04:22

标签: php arrays sorting

$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"];
});

我需要在PHP中对多维数组进行排序。是否有可能按名称对国家进行排序?我试图在usort中实现,但我只能根据名称或国家等条件进行排序。

我想实现MySQL数据库正在做的事情。 像

这样的东西

SELECT * FROM STUDENT order by country,name

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

使用array_multisort,我在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);

此印刷品:

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
        )

)