【问题标题】:Multisorting a nested array in php在php中对嵌套数组进行多排序
【发布时间】:2015-08-27 19:12:41
【问题描述】:

我从几个数据库中提取了一堆内容并编译成这样的嵌套数组:

Array
(
    [0] => Array
        (
            [id] => 3
            [published] => 1433940002
            [content] => This is some content
        )
     [1] => Array
        (
            [id] => 52
            [published] => 1433940001
            [content] => This is some more content
        )
     [2] => Array
        (
            [id] => 16
            [published] => 1433940003
            [content] => This is some more content
        )
)

由于我无法在检索内容时对其进行排序(因为它是使用来自尽可能多的数据库的多个查询完成的)我想在数组中挖掘一个级别并按“发布”日期排序,同时保持深度数组,所以我最终得到...

Array
(
    [0] => Array
        (
            [id] => 52
            [published] => 1433940001
            [content] => This is some more content
        )
     [1] => Array
        (
            [id] => 3
            [published] => 1433940002
            [content] => This is some content
        )
     [2] => Array
        (
            [id] => 16
            [published] => 1433940003
            [content] => This is some more content
        )
)

我很确定 array_multisort() 是要走的路,但我想不出从哪里开始!有没有好心人指点一下?

【问题讨论】:

  • 谢谢@Rizier123 - 这足以将我推向正确的方向!
  • 不客气。享受你的一天:)
  • 这里是晚上11点!我的大脑开始停止运转;)不过我明天会努力享受的!
  • 对我来说也一样。 但请稍等!您还有 1 分钟的时间来享受这一天 :)(不,现在很晚,现在您可以享受接下来的 24 小时)

标签: php arrays sorting multidimensional-array


【解决方案1】:

感谢@Rizier123 对我的问题的监管,我自己想通了。对于其他找到此线程的人,这是我使用上面提供的示例数组的解决方案。

//-- get disorganised content from databases here

usort($array, "publishcmp");

//-- output organised content here

function publishcmp($a , $b){
    if ($a['published'] == $b['published']) {
        return 0;
    }
    return ($a['published'] < $b['published']) ? -1 : 1;
}

几乎从php.net逐字逐句

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多