如何在PHP中合并CSV行


How to merge lines of CSV in PHP

我有一个CSV文件,看起来像:

Andrew Smith, andy@hotmail.co.uk,曼彻斯特,英国
Martin Jones,martin@gmail.com, Reading, UK
雪莉·安德鲁斯,洛杉矶,
Bob James, bobjames@yahoo.com,,

Jacob Costelloe, jc@email.com,悉尼,澳大利亚
Shirley Andrews, shirley@mail.com,, US
Callum Jones, callumjjones@btinternet.com,巴黎,法国
Bob James,伦敦,英国

根据第一列(名称),我需要合并数据,因此从中返回的结果是:

Andrew Smith, andy@hotmail.co.uk,曼彻斯特,英国
Martin Jones,martin@gmail.com, Reading, UK
Bob James, bobjames@yahoo.com,伦敦,英国
Jacob Costelloe, jc@email.com,悉尼,澳大利亚
Shirley Andrews, shirley@mail.com,洛杉矶,美国
Callum Jones, callumjjones@btinternet.com,巴黎,法国

是否有一个简单的方法在PHP中做到这一点?

这样怎么样: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);

这将按照您描述的方式格式化文本:

$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;
       }
    }
}