在PHP中的两列上对多维数组进行排序

时间:2014-03-10 09:50:56

标签: php arrays sorting

有人请帮我解决这个问题。

这是我的阵列 - 我想按shop_featured订购并计算。

Array
(
    [0] => stdClass Object
        (
            [shop_id] => 1
            [shop_featured] => 1
            [counts] => 20
        )

    [1] => stdClass Object
        (
            [shop_id] => 484
            [shop_featured] => 1
            [counts] => 9
        )

    [2] => stdClass Object
        (
            [shop_id] => 886
            [shop_featured] => 0
            [counts] => 0
        )

    [3] => stdClass Object
        (
            [shop_id] => 1279
            [shop_featured] => 0
            [counts] => 0
        )

    [4] => stdClass Object
        (
            [shop_id] => 861
            [shop_featured] => 0
            [counts] => 0
        )

    [5] => stdClass Object
        (
            [shop_id] => 242
            [shop_featured] => 0
            [counts] => 0
        )

    [6] => stdClass Object
        (
            [shop_id] => 1187
            [shop_featured] => 0
            [counts] => 0
        )

    [7] => stdClass Object
        (
            [shop_id] => 906
            [shop_featured] => 0
            [counts] => 2
        )

    [8] => stdClass Object
        (
            [shop_id] => 297
            [shop_featured] => 0
            [counts] => 9
        )

    [9] => stdClass Object
        (
            [shop_id] => 838
            [shop_featured] => 0
            [counts] => 9
        )

    [10] => stdClass Object
        (
            [shop_id] => 1181
            [shop_featured] => 0
            [counts] => 2
        )

    [11] => stdClass Object
        (
            [shop_id] => 620
            [shop_featured] => 0
            [counts] => 0
        )

)

我使用了以下功能

usort($value, array('model_shop', 'cmp1'));
usort($value, array('model_shop', 'cmp'));


function cmp($a, $b)
{
    if ($a->shop_featured == $b->shop_featured) {
    return 0;
    }
    return ($a->shop_featured < $b->shop_featured) ? 1 : -1;
}

function cmp1($a, $b)
{
    if ($a->counts == $b->counts) {
    return 0;
    }
    return ($a->counts < $b->counts) ? 1 : -1;
}

提前谢谢

1 个答案:

答案 0 :(得分:1)

这样的东西应按shop_featured排序,然后计算

usort($value, array('model_shop', 'cmp'));

function cmp($a, $b)
{
    if ($a->shop_featured == $b->shop_featured) {
        if ($a->counts == $b->counts) {
            return 0;
        }
        return ($a->counts < $b->counts) ? 1 : -1;
    }
    return ($a->shop_featured < $b->shop_featured) ? 1 : -1;
}