【问题标题】:Problem with Laravel Collection sortBy functionLaravel Collection sortBy函数的问题
【发布时间】:2021-06-28 19:23:23
【问题描述】:

我正在尝试对一个集合执行多个 sortBy,但似乎无法正常工作:

$myCollection = collect([
    ['foo' => 3, 'bar' => null, 'active' => 1],
    ['foo' => 2, 'bar' => null, 'active' => 1],
    ['foo' => 1, 'bar' => 1, 'active' => 1],
])->sortBy('foo')->sortBy('bar')->sortBy('active');

结果:

Illuminate\Support\Collection {#417 ▼
  #items: array:3 [▼
    0 => array:3 [▼
      "foo" => 3
      "bar" => null
      "active" => 1
    ]
    1 => array:3 [▼
      "foo" => 2
      "bar" => null
      "active" => 1
    ]
    2 => array:3 [▼
      "foo" => 1
      "bar" => 1
      "active" => 1
    ]
  ]
}

首先按活动正确排序(它们都相同 = 1)

然后按“bar”正确排序(null

然后 sortBy('foo') 失败,因为 (2

Illuminate\Support\Collection {#417 ▼
  #items: array:3 [▼
    0 => array:3 [▼
      "foo" => 2
      "bar" => null
      "active" => 1
    ]
    1 => array:3 [▼
      "foo" => 3
      "bar" => null
      "active" => 1
    ]
    2 => array:3 [▼
      "foo" => 1
      "bar" => 1
      "active" => 1
    ]
  ]
}

这是我为演示所做的示例。在我的真实场景中,我使用 Collection::macro 和自定义函数回调来比较日期......但即使在这个简单的例子中,事情看起来也不起作用。

【问题讨论】:

    标签: laravel sorting collections


    【解决方案1】:

    您正在链接三个不同的排序,在这种情况下,您可以确定只有最后应用的排序已正确完成。

    所以尝试传递排序操作数组:

    $myCollection = collect(...)->sortBy([
        ['foo', 'asc'],
        ['bar', 'asc'],
        ['active', 'asc'],
    ]);
    

    您可以在documentation 中找到更多信息。

    【讨论】:

    • 好的,谢谢。我刚看到。谢谢你。 $myCollection = collect([ ['foo' => 3, 'bar' => null, 'active' => 1], ['foo' => 2, 'bar' => null, 'active' => 1 ], ['foo' => 1, 'bar' => 1, '活动' => 1], ]); $sorted = $myCollection->sortBy([ fn ($a, $b) => $a['active'] $b['active'], fn ($a, $b) => $a ['bar'] $b['bar'], fn ($a, $b) => $a['foo'] $b['foo'], ]);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2018-03-22
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 2018-08-29
    相关资源
    最近更新 更多