如何在不同的行上划分用逗号分隔的数据


How can I divide data separated by commas on different lines

我有一个脚本,它从数据库中提取一个.csv文件,该文件保存用户登录的不同本地文件的数据。.csv文件如下所示:

"id_user";"id_local"
"1";""
"2";"2,3,4"
"3";""
"5";"2,5"
"10";""
"13";"2"
"14";"5"
"15";"2"
"16";"1"
"20";"2"
"21";""

正如您所看到的,它为每个用户提供一个寄存器但是,为了正确地操纵它,我们需要这样的:

"id_user";"id_local"
"2";"2"
"2";"3
"2";"4"
"5";"2"
"5";"5"
"13";"2"
"14";"5"
"15";"2"
"16";"1"
"20";"2"

因此,我需要创建一个函数,删除没有本地的用户,并在不同的寄存器中拆分同一用户的不同本地。有人知道我该怎么做吗?

这是我到目前为止的代码,但我不确定我是否走对了方向:

function fix_local_secundario(){
    $filename = "local_secundario.csv";
    $file_locais = file_get_contents($filename);
    $locais = explode("'n", $file_locais);
    // $pattern = "/,/";
    // $replacement = "'"'n;'"";
    while ($line = current($locais)) {
        $line = str_getcsv($line, ';', '"',''n');
        // $line = preg_replace($pattern, $replacement, $line);
        var_dump($line);
        echo "'n";
        next($locais);
    }
}

试试这个,看看它是否有效:

function fix_local_secundario(){
    $filename = "local_secundario.csv";
    $file_locais = file_get_contents($filename);
    $locais = explode("'n", $file_locais);
    while ($line = current($locais)) {
        // do first split on ; character
        $arr1 = explode(";", $line);
        // if the part after ; is not empty for this line
        if ($arr1[1]!='""'){
            // split it further on , character
            $arr2 = explode(",", $arr1[1]);
            foreach ($arr2 as $key => $val){
                if($val[0] != '"'){
                    $val = '"'.$val;
                }
                if($val[strlen($val)-1] != '"'){
                    $val = $val . '"';
                }
                echo $arr1[0] . ";" . $val . "<BR>";
            }
        }
        next($locais);
    }
}

一旦这个基本部分开始工作,您应该将其更改为返回值,而不是回显值,因为根据对您的问题所做的更新,此代码是函数的一部分。

这个…怎么样

$f = fopen("myfile.csv", "r");
while($row = fgetcsv($f, 0, ";")){
  $locals = explode(",", $row[1]);
  if (count($locals)>1){
    foreach($locals as $local)
      // iterate with $row[0] and $local
  }elseif($row[1] != "")
      // use $row[0] and $row[1]
}