【问题标题】:How to sort a collection in Laravel如何在 Laravel 中对集合进行排序
【发布时间】:2020-05-27 09:41:24
【问题描述】:

我正在使用 sortBy 函数进行排序,但我不能使用它作为按 For 排序。

$this->journey->journey_item = $this->journey->journey_items->sortBy('activation_date');
dump($journey_items); //// sorted list

for($i = 0;$i < Count($this->journey->journey_item);$i++){
   dump("#".$i." ".$this->journey->journey_item[$i]->activation_date);
}

当它进入 For 时,它变成未排序的。 我在哪里做错了? 我能做什么?

另外,我创建了一个新集合并尝试均衡它,但它没有

【问题讨论】:

    标签: laravel collections


    【解决方案1】:

    尝试使用 foreach。当您使用集合排序时,它会对您的数组进行排序而不是key.. 因为我看到您使用的是key [$i]

    使用 foreach

    foreach($this->journey->journey_item as $journey_item){
       dump($journey_item);
    }
    

    或者你使用如下。

    $this->journey->journey_item = $this->journey->journey_items->sortBy(function ($journey_item) {
        return $journey_item->activation_date;
    });
    

    【讨论】:

    • 第二个解决方案,它给了我错误; asort() 期望参数 2 是 int, object given
    • sortBy函数中如何指定activation_date
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2021-01-15
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多