如何解决解析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档案: 老顾客;新顾客 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解析(从这里被盗)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;
}
解决方法
查看爆炸功能。拿起您的字符串并运行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);
, 您可以使用以下代码解决您的问题
$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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。