dsfdsfds521521 2019-04-21 19:34
浏览 127
已采纳

Laravel:按单个字符串中的姓氏对集合进行排序

i'm trying to sort a collection, which consists of ids and full names, alphabetically by the last name. the id comes from a parent class and the full name from the child.

I tried exploding the string and ordering according to the last name, but couldn't really get it to also reorder th IDs properly. I tried both with sortBy while getting the collection and with usort after retrieving it

$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]);

The code above works fine for sorting it by first name, but I need it to sort by last name.

user inputs test_id, which gives a list of "TestExaminers", each has a property "examiner_id" associated with a unique "examiner", which in turn has a name "firstname middlename lastname". so it should look something like this

before sort

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

after sort

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

Thanks!

  • 写回答

1条回答 默认 最新

  • douchong8393 2019-04-22 05:39
    关注

    How about trying something like this?

    $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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!