【发布时间】:2014-12-17 02:03:29
【问题描述】:
按字母顺序排序时,我只剩下这个:
S1 Episode 1
S1 Episode 11
S1 Episode 12
S1 Episode 2
S1 Episode 3
S2 Episode 1
S2 Episode 11
示例代码:
DB::table('test')->orderby('title', 'ASC')->get();
等等。我需要正确订购这些。有什么解决办法吗?
谢谢。
【问题讨论】:
按字母顺序排序时,我只剩下这个:
S1 Episode 1
S1 Episode 11
S1 Episode 12
S1 Episode 2
S1 Episode 3
S2 Episode 1
S2 Episode 11
示例代码:
DB::table('test')->orderby('title', 'ASC')->get();
等等。我需要正确订购这些。有什么解决办法吗?
谢谢。
【问题讨论】:
您面临按字母数字排序项目的问题,或者用计算机科学术语,自然排序。
有 many ways to achieve a natural sort with straight MySQL,但您也可以将 Laravel 助手的结果转换为数组格式并实现 PHP 的 natsort function instead。
从上面找到的方法中,我得出了可能使用示例代码解决您的问题的最佳方法:
DB::table('test')->orderBy('LENGTH(title)', 'ASC')
->orderBy('title', 'ASC')
->get();
但是我不确定助手是否会抱怨在orderBy 函数中接收 MySQL 函数而不是直接列名。我也只是根据我与您的示例结合使用的参考文献进行转录-我不能保证其有效性。
【讨论】:
对于 Laravel,这也适用:
$collection = $collection->sortBy('order', SORT_REGULAR, true);
【讨论】:
可能会迟到,但对其他人可能会有所帮助。
根据我在下面找到的上述链接,我得出了可能使用示例代码解决您的问题的最佳方法: https://www.electrictoolbox.com/mysql-order-string-as-int/
查询
SELECT * FROM <table> ORDER BY CAST(<column> AS unsigned)
laravel 示例
DB::table('test')
->orderByRaw("CAST(title as UNSIGNED) ASC")
->get();
【讨论】:
DB::table('test')->orderByRaw('LENGTH(title)', 'ASC')
->orderBy('title', 'ASC')
->get();
【讨论】:
对于 Laravel 集合:
$collection = collect([
['sn' => '2'],
['sn' => 'B'],
['sn' => '1'],
['sn' => '10'],
['sn' => 'A'],
['sn' => '13'],
]);
$sorted = $collection->sortBy('sn');
//print_r($collection);
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[2] => Array
(
[sn] => 1
)
[0] => Array
(
[sn] => 2
)
[3] => Array
(
[sn] => 10
)
[5] => Array
(
[sn] => 13
)
[4] => Array
(
[sn] => A
)
[1] => Array
(
[sn] => B
)
)
)
如您所见,这将正确排序。但是,如果您想对其进行排序并重新索引,则
$sorted = $collection->sortBy('sn')->values()->all();
//print_r($sorted)
Array
(
[0] => Array
(
[sn] => 1
)
[1] => Array
(
[sn] => 2
)
[2] => Array
(
[sn] => 10
)
[3] => Array
(
[sn] => 13
)
[4] => Array
(
[sn] => A
)
[5] => Array
(
[sn] => B
)
)
此外,您还可以传递自己的回调来确定如何对集合值进行排序。
$sorted = $collection->sortBy(function ($item, $key) {
//your logic
});
【讨论】:
对结果集合排序
$unorderedThings = Thing::orderBy('id')->get();
$orderedThings=$unorderedThings->sort();
【讨论】:
这个作品是我用eloquent做的,很简单:
口才:
$tests = Test::all();
$tests = $tests->sortBy('title', SORT_REGULAR, false); // false=ascending, true=descending
在 Laravel 中将数字排序为文本。
希望对你有帮助
【讨论】: