dougang6821 2011-10-31 15:59
浏览 91
已采纳

PHP MySQL提取字段然后在双空格分割

I have a table which contains rows, within each row there is a field which contains peoples names seperated by a double space.

I need to extract this field from each row, then split the field into separate names and dump into another table.

What's the best way to do this? Do I split it within the sql query or extract the fields then split using PHP?

New info:

OK, the field contains full names e.g. john doe, tom smith etc etc the double spaces separate the full names e.g.

JOHN DOE  TOM SMITH  JOHN WOO

There might be one name in the field but there could also be potentialy up to 10

Thanks

Darren

  • 写回答

2条回答 默认 最新

  • doujin8476 2011-10-31 16:06
    关注

    you can do it in sql. should be something like this:

    INSERT INTO tbl_dest (first_name, last_name) VALUES
    
    (SELECT
        LEFT(ts.name, LOCATE('  ',ts.name)) AS first_name,
        SUBSTRING(ts.name, LOCATE('  ',ts.name)+2) AS last_name
    FROM tbl_source AS ts)
    

    as @Marc B stated, it will only work if the data is consistent (ie each row's name field contains a double space and the first double space separates the name and password. you can ignore other rows (without the double space) by simply adding

    INSERT ...
    (SELECT   ... 
    FROM tbl_source AS ts WHERE LOCATE('  ', ts.name) > 0)
    

    if the field starts with a double space (ie first name is empty) it will also be ignored

    EDIT:

    since you said that each row can contain multiple pairs of first/last name. here's a code example:

    $query = "SELECT `name` FROM `tbl_source`";
    $res = mysql_query($query, $link);
    $names = array();
    while ($row = mysql_fetch_assoc($res)) {
        $nmlist = explode('  ',$row['name']);
        for($i=0, $n=count($nmlist); $i<$n-1; $i+=2){
            $names[] = "('" . mysql_real_escape_string(stripslashes($nmlist[$i])) ."',"
                       ."'" . mysql_real_escape_string(stripslashes($nmlist[$i+1])) ."')";
        }
    }
    $insert_query = "INSERT INTO `tbl_dest` (`first_name`,`last_name`) VALUES "
              .implode(',', $names);
    mysql_query($insert_query, $link);
    

    in this example, double spaces are between first name and last name, and between each pair

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

报告相同问题?

悬赏问题

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