Laravel 集合 sortBy 函数有问题
Problem with Laravel Collection sortBy function
我正在尝试对一个集合进行多重排序,但似乎无法正常工作:
$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<3),但在 2 之前先显示 3 ...
预期结果:
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 和自定义函数回调来比较日期......但即使在这个简单的例子中,事情看起来也不起作用。
您正在链接三个不同的排序,在这种情况下,您可以确定只有最后应用的排序已正确完成。
所以尝试传递排序操作数组:
$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, '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<3),但在 2 之前先显示 3 ... 预期结果:
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 和自定义函数回调来比较日期......但即使在这个简单的例子中,事情看起来也不起作用。
您正在链接三个不同的排序,在这种情况下,您可以确定只有最后应用的排序已正确完成。
所以尝试传递排序操作数组:
$myCollection = collect(...)->sortBy([
['foo', 'asc'],
['bar', 'asc'],
['active', 'asc'],
]);
您可以在 documentation 中找到更多信息。