【问题标题】:Laravel: sorting collection by last name in single stringLaravel:按单个字符串中的姓氏对集合进行排序
【发布时间】:2019-04-21 19:34:33
【问题描述】:

我正在尝试按姓氏的字母顺序对包含 ID 和全名的集合进行排序。 id 来自父类,全名来自子类。

我尝试分解字符串并根据姓氏进行排序,但无法真正正确地重新排序 ID。 我在获取集合时尝试了 sortBy 并在检索集合后尝试了 usort

$testExaminers=TestExaminer::where('test_id',$request->testid)
->with('examiner')
->get()
->sortBy('examiner.name');

$result = array();
$num=0;
foreach($testExaminers as $testExaminer) {
            $result[$num]['id'] = (int) $testExaminer->examiner_id;
            $result[$num]['text'] = $testExaminer->examiner->name;
            $num++;
}

echo json_encode(['examiners'=>$result]);

上面的代码可以很好地按名字排序,但我需要它按姓氏排序。

用户输入 test_id,它给出了一个“TestExaminers”列表,每个都有一个属性“examiner_id”,该属性与一个唯一的“examiner”相关联,而该属性又具有一个名称“firstname middlename lastname”。 所以它应该看起来像这样

排序前

$result = [[1,'Alpha Z. Goodman'],[2,'Joe Bman'],[3,'ZZ Top'],[4,'Joe Aman']]

排序后

$result = [[4,'Joe Aman'],[2,'Joe Bman'],[1,'Alpha Z. Goodman'],[3,'ZZ Top']]

谢谢!

【问题讨论】:

    标签: php laravel sorting


    【解决方案1】:

    试试这样的怎么样?

    $testExaminers = TestExaminer::where('test_id', $request->testid)
        ->with('examiner')
        ->get()
        ->map(function ($item, $key) {
            $item->examiner->last_name = array_slice(explode(' ', $item->examiner->name), -1)[0];
    
            return $item;
        })
        ->sortBy('examiner.last_name');
    

    【讨论】:

    • 谢谢,工作就像一个魅力!我不知道 map() 及其工作原理
    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2019-05-06
    • 2015-07-08
    • 2010-10-26
    相关资源
    最近更新 更多