我的CSV文件类似于:
Andrew Smith,andy @ hotmail.co.uk,英国曼彻斯特(Martin Jones),Martin Jones, martin@gmail.com,英国雷丁 Shirley Andrews,洛杉矶,
Bob James,bobjames @ yahoo.com,
Jacob Costelloe,jc @ email.com,澳大利亚悉尼
Shirley Andrews,shirley @mail.com,美国
Callum Jones,callumjjones @ btinternet.com,法国巴黎
Bob James,英国伦敦
基于第一列(名称),我需要合并数据,所以从这里返回我会得到:
Andrew Smith,andy @ hotmail.co.uk,英国曼彻斯特(Martin Jones),Martin Jones, martin@gmail.com,英国雷丁 Bob James,bobjames @ yahoo.com,英国伦敦
Jacob Costelloe,jc @ email.com,澳大利亚悉尼
Shirley Andrews,shirley @mail.com,洛杉矶,美国
Callum Jones,callumjjones @ btinternet.com,法国巴黎
在PHP中有一种简单的方法吗?
答案 0 :(得分:1)
这样的事情:http://codepad.org/MfYAycZk
正如您所看到的,输出将两个Bob James联系在一起。
$text = "Andrew Smith, andy@hotmail.co.uk, Manchester, UK
Martin Jones, martin@gmail.com, Reading, UK
Shirley Andrews, , Los Angeles,
Bob James, bobjames@yahoo.com, ,
Jacob Costelloe, jc@email.com, Sydney, Australia
Shirley Andrews, shirley@mail.com, , US
Callum Jones, callumjjones@btinternet.com, Paris, France
Bob James, , London, UK";
$people = array();
foreach( explode( "\n", $text) as $line)
{
$entries = explode( ',', $line);
$entries = array_map( 'trim', $entries);
list( $first_name, $last_name) = explode( ' ', $entries[0]);
if( isset( $people[ $last_name ][ $first_name ])) {
$people[ $last_name ][ $first_name ] = array_merge( $people[ $last_name ][ $first_name ], array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $entries[1],
'city' => $entries[2],
'country' => $entries[3]
));
} else {
$people[ $last_name ][ $first_name ] = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $entries[1],
'city' => $entries[2],
'country' => $entries[3]
);
}
}
var_dump( $people);
答案 1 :(得分:0)
这将格式化您描述的文字:
$text = str_replace("\r", '', $text);
$container = explode("\n", $text);
$rows = array();
foreach ($container as $data) {
$values = array_map('trim', explode(',', $data));
$id = strtolower(trim($values[0]));
if ($id) {
if (true == isset($rows[$id])) {
//remove blank
$values = array_filter($values);
foreach ($values as $i => $value) {
if ($rows[ $id ][ $i ] == '') {
$rows[ $id ][ $i ] = $value;
}
}
} else {
$rows[ $id ] = $values;
}
}
}