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

报告相同问题?

悬赏问题

  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题
  • ¥15 一道计算机组成原理问题