如何按定义键PHP

时间:2016-04-09 14:44:29

标签: php arrays sorting

想要按键的值对数组进行排序,但无法在网络中找到解决方案。

我希望在PHP中使用密钥is_paid对此数组DESC进行排序,以便从原始数组:

[user_courses] => Array
    (
        [1] => Array
            (
                [paid_course_id] => 1
                [course_name] => english
                [course_label] => English
                [is_paid] => 1
                [time] => 1378925144
                [voucher] => 0
            )

        [2] => Array
            (
                [paid_course_id] => 2
                [course_name] => spanish
                [course_label] => English
                [is_paid] => 0
                [time] => 1379073137
                [voucher] => 0
            )

        [3] => Array
            (
                [paid_course_id] => 3
                [course_name] => russian
                [course_label] => Russian
                [is_paid] => 1
                [time] => 1452277777
                [voucher] => 0


    )
)

成为:

[user_courses] => Array
(
[1] => Array
    (
        [paid_course_id] => 1
        [course_name] => english
        [course_label] => English
        [is_paid] => 1
        [time] => 1378925144
        [voucher] => 0
    )
[3] => Array
    (
        [paid_course_id] => 3
        [course_name] => russian
        [course_label] => Russian
        [is_paid] => 1
        [time] => 1452277777
        [voucher] => 0


)

[2] => Array
    (
        [paid_course_id] => 2
        [course_name] => spanish
        [course_label] => English
        [is_paid] => 0
        [time] => 1379073137
        [voucher] => 0
    )


)

首先列出数组的所有项目,其中is_paid为1,数组底部放入is_paid 0

1 个答案:

答案 0 :(得分:0)

function sortOrder($a, $b) {
    return $a['paid_course_id'] > $b['paid_course_id'];
}

usort($courseArray['user_courses'], 'sortOrder');

或匿名函数

usort($courseArray['user_courses'], function($a, $b) {
    return $a['paid_course_id'] > $b['paid_course_id'];
});