dongpu42006096 2014-08-29 07:43
浏览 307
已采纳

从MySQL中选择 - 只有姓氏的首字母

I have a question when doing the selection from a database:

A column from one of my tables contains the name from persons. Let's say it looks like this:

 1. John Smith
 2. William Thorne
 3. Mark Johanson

Ok, I have shown you some examples of some random names.

The thing is that both, the first name, and the last name are in the same column, and the result I want to come to, when I'm doing the selection in my php file is this:

1. John S.
2. William T.
3. Mark J.

I want that from the last name of each person, to be shown only the initial of the last name. Is there a possibility to do this? If there is, any help would be great.

My code selection example is here:

$result = mysql_query("SELECT * FROM feedback_rate 
                       WHERE accept=1 
                       ORDER BY date DESC 
                       LIMIT $start,$rows_per_page",$con);

Thank you for the help in advance.

  • 写回答

2条回答 默认 最新

  • dpoxk64080 2014-08-29 07:55
    关注

    You have to realise that this is extremely difficult to do right. Computers don't know about names, they have no idea what's a first name and what's a last name. You therefore will have to make assumptions which aren't always true. I make the assumption that there's always only one first name. Then it is easy to solve in PHP with the following steps:

    1. Split name into words.
    2. Change the last word.
    3. put them back together again.

    This is how that is done:

    $parts = explode(' ',$fullName);
    $firstName = array_pop($parts);
    $initial = substr($firstName,0,1);
    array_push($parts,$initial.'.');
    $fullName = implode(' ',$parts);
    

    And now $fullName will contain what you wanted. The code look a bit long but that's because I try to show it step by step.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用yolov5-7.0目标检测报错
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备