【问题标题】:How to sort a collection of UTF-8 strings containing non-Latin chars in Laravel 5.3?如何在 Laravel 5.3 中对包含非拉丁字符的 UTF-8 字符串集合进行排序?
【发布时间】:2017-01-15 10:28:22
【问题描述】:

伙计们,我想排序以下嵌套的collection 按字符串 字母顺序:

$collection = collect([
    ["name"=>"maroon"],
    ["name"=>"zoo"],
    ["name"=>"ábel"],
    ["name"=>"élof"]
])->sortBy("name");

我希望:

1=> "ábel"
2=> "élof"
3=> "maroon"
4=> "zoo"

我得到了:

1=> "maroon"
2=> "zoo"
3=> "ábel"
4=> "élof"

我看到了一些 PHP 线程,但我很好奇是否有任何 Laravel 解决方法。谢谢。

【问题讨论】:

    标签: sorting utf-8 laravel-5.3 collation laravel-collection


    【解决方案1】:

    这是一个可靠的方法:

    $blank = array();
    $collection = collect([
        ["name"=>"maroon"],
        ["name"=>"zoo"],
        ["name"=>"ábel"],
        ["name"=>"élof"]
    ])->toArray();
    
    $count = count($collection);
    
    for ($x=0; $x < $count; $x++) { 
        $blank[$x] = $collection[$x]['name'];
    }
    
    $collator = collator_create('en_US');
    var_export($blank);
    collator_sort( $collator, $blank );
    var_export( $blank );
    
    dd($blank);
    

    输出:

    array (
      0 => 'maroon',
      1 => 'zoo',
      2 => 'ábel',
      3 => 'élof',
    )array (
      0 => 'ábel',
      1 => 'élof',
      2 => 'maroon',
      3 => 'zoo',
    )
    

    Laravel 漂亮的输出:

    array:4 [
      0 => "ábel"
      1 => "élof"
      2 => "maroon"
      3 => "zoo"
    ]
    

    供个人阅读和参考: http://php.net/manual/en/class.collator.php

    希望这个答案有帮助,抱歉回复晚了=)

    【讨论】:

      【解决方案2】:

      在这种情况下,您不需要使用 Collat​​or 类。 Laravel 的集合 sortBy 内部使用 asort() 和 arsort(),其中有 SORT_LOCALE_STRING 标志用于根据当前设置的语言环境。

      所以,你的例子可以写成如下:

      setlocale(LC_COLLATE, 'fr_FR.utf8'); // No need to set this if you're doing it elsewhere
      
      $collection = collect([
          ["name"=>"maroon"],
          ["name"=>"zoo"],
          ["name"=>"ábel"],
          ["name"=>"élof"]
      ])->sortBy("name", SORT_LOCALE_STRING); // Signals to arsort() to take locale into consideration
      

      这也意味着您不必从通用 PHP 数组到 Laravel 集合来回转换。

      【讨论】:

        【解决方案3】:

        好吧,我遇到了这个问题,我能够像这样解决它:

        $list = $Company->administrator->sortBy(function($adm){
           return iconv('UTF-8', 'ASCII//TRANSLIT', $adm->person->name);
        });
        

        我的环境是 Laravel 5.5 和 PHP 7.1

        【讨论】:

        • 在某些情况下,您可能希望在排序依据的属性上添加strtolower
        猜你喜欢
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        • 2019-04-09
        • 2010-11-02
        • 2023-03-10
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        相关资源
        最近更新 更多