按内部值对多维数组进行排序

时间:2014-10-23 12:04:24

标签: php arrays sorting

我想使用PHP函数按status_id对数组进行排序。我怎么能这样做呢?

以下是数组的示例:

Array
(
    [0] => stdClass Object
        (
            [status_id] => 4
            [status_content] => {"text":"DET VIRKER JO IKKE!!!! ### >"}
            [status_likes] => 
            [status_dislikes] => 
            [status_owner] => 20
        )

    [1] => stdClass Object
        (
            [status_id] => 2
            [status_content] => {"yt_vid":"Hb3MWuZT_W0","text":"Det her er jo bare awesome!!!"}
            [status_likes] => 
            [status_dislikes] => 
            [status_owner] => 20
        )

    [2] => stdClass Object
        (
            [status_id] => 8
            [status_content] => {"text":"Hej"}
            [status_likes] => 
            [status_dislikes] => 
            [status_owner] => 1
        )

    [3] => stdClass Object
        (
            [status_id] => 7
            [status_content] => {"text":"ff"}
            [status_likes] => 
            [status_dislikes] => 
            [status_owner] => 1
        )

    [4] => stdClass Object
        (
            [status_id] => 6
            [status_content] => {"text":"h"}
            [status_likes] => 
            [status_dislikes] => 
            [status_owner] => 1
        )

    [5] => stdClass Object
        (
            [status_id] => 5
            [status_content] => {"text":""}
            [status_likes] => 
            [status_dislikes] => 
            [status_owner] => 1
        )

    [6] => stdClass Object
        (
            [status_id] => 3
            [status_content] => {"yt_vid":"PSLDZVh1Vtw","text":"This is really funny"}
            [status_likes] => 
            [status_dislikes] => 
            [status_owner] => 1
        )

    [7] => stdClass Object
        (
            [status_id] => 1
            [status_content] => {"text":"This works, great! huh?"}
            [status_likes] => 
            [status_dislikes] => 
            [status_owner] => 1
        )

)

3 个答案:

答案 0 :(得分:0)

您需要使用array_multisort

http://php.net/manual/en/function.array-multisort.php

首先循环获取玩具希望排序的所有项目的简单数组(状态ID),然后将该变量与您想要在array_multisort中排序的数组一起使用

答案 1 :(得分:0)

一种选择是使用usort和自定义排序功能。这是一个基于某个属性名称为您构建闭包的小函数:

function buildSorter($key) {
    return function ($a, $b) use ($key) { return strnatcmp($a->$key, $b->$key); };
}

使用它,您可以:

usort($data, buildSorter('status_content'));

usort($data, buildSorter('status_owner'));

同样轻松。

答案 2 :(得分:0)

谢谢你的帮助!我知道终于找到了答案,看起来好一点。

看看。

usort($r, function($a, $b) { return $a['status_id'] - $b['status_id']; });