Laravel Collection sortBy函数存在问题

Laravel Collection sortBy函数存在问题,laravel,sorting,collections,Laravel,Sorting,Collections,我试图对一个集合进行多次排序,但似乎无法正常工作: $myCollection = collect([ ['foo' => 3, 'bar' => null, 'active' => 1], ['foo' => 2, 'bar' => null, 'active' => 1], ['foo' => 1, 'bar' => 1, 'active' => 1], ])->sortBy('foo')->sortB

我试图对一个集合进行多次排序,但似乎无法正常工作:

$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)

然后按“条”正确排序(null<1)


然后sortBy('foo')失败,因为(2您正在链接三个不同的排序,在这种情况下,您只能确保最后应用的排序已正确完成

因此,请尝试传递排序操作数组:

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

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

是的,谢谢。我刚刚看到了。谢谢。$myCollection=collect([['foo'=>3,'bar'=>null,'active'=>1],'foo'=>2,'bar'=>null,'active'=>1,'foo'=>1,'bar'=>1,];$sorted=$myCollection->sortBy([fn($a,$b=>a['active'>a['active']b]>a['active'>fn,$b']=>a['bar']$b['bar'],fn($a,$b)=>a['foo']$b['foo'],]);
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
    ]
  ]
}