Laravel/PHP:按字母顺序排列,数字按顺序排列


Laravel/ PHP: Order By Alphabetical with numbers in order

当按字母顺序排序时,我只剩下以下内容:

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();

等等。我需要正确订购这些。有什么解决方案吗?

谢谢。

您面临着按字母数字排序项目的问题,或者用计算机科学的术语来说,是自然排序

有很多方法可以使用直接MySQL实现自然排序,但您也可以将Laravel助手的结果转换为数组格式,并实现PHP的natsort函数。

从我上面找到的方法中,我得出了可能用示例代码解决问题的最佳方法:

DB::table('test')->orderBy('LENGTH(title)', 'ASC')
    ->orderBy('title', 'ASC')
    ->get();

然而,我不确定助手是否会抱怨接收到MySQL函数,而不是orderBy函数中的直接列名。我只是从我结合你的例子使用的参考文献中转录出来——我不能保证有效性。

可能会迟到,但对其他人来说可能会有所帮助。

基于我在下面找到的上述链接,我用示例代码推导出了可能解决您问题的最佳方法: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();

对于Laravel来说,这也适用:

$collection = $collection->sortBy('order', SORT_REGULAR, true);
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
});

有关更多详细信息:https://laravel.com/docs/5.8/collections#method-按排序

基本上类似于已接受的答案,但去掉了逗号和orderByRaw。否则我会得到一个关于绑定的错误

DB::table('test')->orderByRaw('LENGTH(title) ASC') ->orderBy('title', 'ASC') ->get();

订购生成的集合

$unorderedThings = Thing::orderBy('id')->get();
$orderedThings=$unorderedThings->sort();

这项工作对我来说是使用雄辩的,非常简单:

Eloquent

$tests = Test::all();
$tests = $tests->sortBy('title', SORT_REGULAR, false); // false=ascending, true=descending

在Laravel中将数字作为文本进行排序

我希望这对非常有帮助