繁体   English   中英

将数据拆分为多列

[英]Split data to multiple columns

这是当前位于一列中的数据:

“标题信息-公司在这里-ST在这里”

ST代表状态,即GA

有时我的数据如下所示:

“标题信息-公司在这里-美国”

数据位于名为“ title”的列上,并且不带引号。

我该如何使用php拆分这四个新列:

“ New_Title”,“公司”,“城市”,“州”

在第二个示例中,没有城市和州只是国家/地区,可以进入“城市”列。

表架构:

CREATE TABLE table ( 
id int(8) NOT NULL DEFAULT '0', 
Title char(100) DEFAULT NULL, 
New_Title char(100) DEFAULT NULL, 
Company char(100) DEFAULT NULL, 
City char(100) DEFAULT NULL, 
State char(100) DEFAULT NULL, 
PRIMARY KEY (id) 
) 
ENGINE=MyISAM DEFAULT CHARSET=latin1; 

谢谢你的时间。

奥西

首先在“-”上拆分,然后拆分在“,”上返回的第三个元素

<?PHP
$title = $row['title']; // or however you get the title.
$parts = explode("-",$title);
if ( count($parts) != 3) die("Invalid title: $title");
$newtitle = $parts[0];
$company = $parts[1];
$location_parts = explode(',',$parts[2]);
$city = $location_parts[0];
$state = $location_parts[1];

//now you've got $newtitle, $company, $city, and $state to do something productive with.

我看到2种方法:

首先:使用regexp之类的

(^[^-]*) - ([^-]*) - ([^,]*),?(.*)$

preg_match

第二:根本不使用php代码。 SQL更新就足够了

UPDATE mytable t SET t.title = SUBSTRING_INDEX(t.value, ' - ', 1), t.company = SUBSTRING_INDEX(SUBSTRING_INDEX(t.value, ' - ', 2), ' - ', -1), t.city = SUBSTRING_INDEX(t.address, ' - ', -1);

接着

UPDATE mytable t SET
t.city = SUBSTRING_INDEX(t.city ',', 1),
t.state = SUBSTRING(t.city, LENGTH(SUBSTRING_INDEX(t.city, ',', 1))+3);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM