奇怪行为解析CSV

问题描述:

我已经解析CSV(2个coloumns)时遇到了一个问题,当 阵列([0] =>数组([0] => oldcustomer 1 => newcostumer 4245945 [2] = > 6773197 4260367 [3] => 6773381 4889300 [4] => 6764472 4740434 [5] => 6764555 4710449 [6] => 6764560奇怪行为解析CSV

我希望它在单独的数组中,并且newcostumerID与“oldcustomer ID”

CSV文件:

oldcustomer; newcostumer
4245945; 6773197
4260367; 6773381
4889300; 6764472
4740434; 6764555
4710449; 6764560
4699714; 6766531
4451642; 6775682
4534699; 6775683
4378586; 6775684
4711005; 6775685
4502714; 6775686
4288738; 6775687

ç SV解析(从here被盗)

function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") { 
// @author: Klemen Nagode 
$array = array(); 
$size = strlen($string); 
$columnIndex = 0; 
$rowIndex = 0; 
$fieldValue=""; 
$isEnclosured = false; 
for($i=0; $i<$size;$i++) { 

    $char = $string{$i}; 
    $addChar = ""; 

    if($isEnclosured) { 
     if($char==$enclosureChar) { 

      if($i+1<$size && $string{$i+1}==$enclosureChar){ 
       // escaped char 
       $addChar=$char; 
       $i++; // dont check next char 
      }else{ 
       $isEnclosured = false; 
      } 
     }else { 
      $addChar=$char; 
     } 
    }else { 
     if($char==$enclosureChar) { 
      $isEnclosured = true; 
     }else { 

      if($char==$separatorChar) { 

       $array[$rowIndex][$columnIndex] = $fieldValue; 
       $fieldValue=""; 

       $columnIndex++; 
      }elseif($char==$newlineChar) { 
       echo $char; 
       $array[$rowIndex][$columnIndex] = $fieldValue; 
       $fieldValue=""; 
       $columnIndex=0; 
       $rowIndex++; 
      }else { 
       $addChar=$char; 
      } 
     } 
    } 
    if($addChar!=""){ 
     $fieldValue.=$addChar; 

    } 
} 

if($fieldValue) { // save last field 
    $array[$rowIndex][$columnIndex] = $fieldValue; 
} 
return $array; 

}

+0

呸。你为什么不使用这个问题中被接受的答案中的代码? – 2011-06-12 18:23:39

看那爆炸功能。带上你的字符串并运行爆炸(“\ n”,$ string)来获取一行数组。然后迭代每一行并在其上爆炸;字符。

$rows = explode("\n",$string); 
$oldcustomer = array(); 
$newcustomer = array(); 
foreach ($rows as $row) { 
    $columns = explode(";",$row); 
    $oldcustomer[] = $columns[0]; 
    $newcustomer[] = $columns[1]; 
} 
print_r($oldcustomer); 
print_r($newcustomer); 
+0

谢谢!在将\ n更改为\ r后,工作就像一个魅力 – moffepoffe 2011-06-12 20:31:38

您可以使用下面的代码来解决你的问题

$row = -1; 
$oldcustomer=array(); 
$newcustomer=array(); 
if (($handle = fopen("yourfile.csv", "r")) !== FALSE) { 
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { 
     if($row==-1){//Skipping first line 
      $row++; 
      continue; 
     } 
     $oldcustomer[$row]=$data[0]; 
     $newcustomer[$row]=$data[1]; 
     $row++; 
    } 
    fclose($handle); 
    print_r($oldcustomer); 
    print_r($newcustomer); 
}