解析CSV时出现奇怪的行为

时间:2011-06-12 18:15:36

标签: php parsing csv

解析CSV时遇到问题(有2个颜色) 数组([0] =>数组([0] => oldcustomer 1 => newcostumer 4245945 [2] => 6773197 4260367 [3] => 6773381 4889300 [4] => 6764472 4740434 [5] => 6764555 4710449 [6] => 6764560

我希望它在单独的数组中,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

CSV Parse(从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;

}

2 个答案:

答案 0 :(得分:1)

查看爆炸功能。拿你的字符串并运行explode(“\ 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);

答案 1 :(得分:0)

您可以使用以下代码解决问题

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