如何通过特定属性对PHP中的关联数组进行排序

时间:2017-07-08 14:24:26

标签: php arrays sorting

我有这个数组。我想排序这个,我怎么能这样做?

 array:2 [▼
      0 => Collection {#198 ▼
        #items: array:2 [▼

      0 => {#201 ▼

        +"id": 2;
        +"title": "Now eldest";
        +"description": "Now eldest new tastes plenty mother called misery get."
        +"created_at": "2017-07-07 16:34:00"
      }

      1 => {#197 ▼

        +"id": 6
        +"title": "dffd"
        +"description": "fdfdfdfdfdffdfdf"
        +"created_at": "2017-07-07 10:23:00"
      }]  }
      1 => Collection {#189 ▼
        #items: array:2 [▼

      0 => {#208 ▼

        +"id": 5
        +"title": "However, if you are not using Homestead"
        +"description": "The Laravel framework has a few system requirements."
        +"created_at": "2017-07-07 13:37:00"
      }

      1 => {#196 ▼

        +"id": 7
        +"title": "fedffdf"
        +"description": "fdfdfdf"
        +"created_at": "2017-07-07 09:12:00"
      }] }]

我正在处理一个应用程序,我希望在时间轴中显示按时间排序的所有帖子&created;<#39;。 我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

尝试usort

usort($collection, function(array $a, array $b) {
    return $a["created_at"] <=> $b["created_at"];
});

如果您使用的是没有<=>运算符的PHP版本,请尝试以下方法:

usort($collection, function(array $a, array $b) {
    return $a["created_at"] >= $b["created_at"] ? 1 : -1;
});

链接到文档:PHP: usort