0

我有这个脚本,它从数据库中提取一个 .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);
    }

}
4

2 回答 2

0

这个呢……</p>

$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]

}
于 2013-08-09T18:19:20.337 回答
0

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

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

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

于 2013-08-09T18:16:40.870 回答