1. 使用类

注意: user.csv 第一行默认为数组的键, 且第一行不会被打印; (区别于下面的普通函数方法 )

例如:

name age gender
zhang 23 male
li 20 female

结果:

Array
([0] => Array([name] => zhang [age] => 23[gender] => male)[1] => Array([name] => li [age] => 20[gender] => female)
)

回到正题:

<?php
//ini_set('memory_limit', '-1'); // 如果csv比较大的话,可以添加。
/**  $file : csv file*  $csvDataArr : header of csv table, eg: arary('name','sex','age') or array(0,1,2)*  $specialhtml : whether do you want to convert special characters to html entities ?*  $removechar : which type do you want to remove special characters in array keys, manual or automatical ?*/
class csv_to_array
{private $counter;private $handler;private $length;private $file;private $seprator;private $specialhtml;private $removechar = 'manual';private $csvDataArr;private $csvData = array();function __construct($file = '', $csvDataArr = '', $specialhtml = true, $length = 1000, $seprator = ','){$this->counter = 0;$this->length = $length;$this->file = $file;$this->seprator =  $seprator;$this->specialhtml =  $specialhtml;$this->csvDataArr = is_array($csvDataArr) ? $csvDataArr : array();$this->handler = fopen($this->file, "r");}function get_array(){$getCsvArr = array();$csvDataArr = array();while(($data = fgetcsv($this->handler, $this->length, $this->seprator)) != FALSE){$num = count($data);$getCsvArr[$this->counter] = $data;$this->counter++;}if(count($getCsvArr) > 0){$csvDataArr = array_shift($getCsvArr);if($this->csvDataArr) $csvDataArr = $this->csvDataArr;$counter = 0;foreach($getCsvArr as $csvValue){$totalRec = count($csvValue);for($i = 0; $i < $totalRec ; $i++){$key = $this->csvDataArr ? $csvDataArr[$i] : $this->remove_char($csvDataArr[$i]);if($csvValue[$i]) $this->csvData[$counter][$key] = $this->put_special_char($csvValue[$i]);}$counter++;}}return $this->csvData;}function put_special_char($value){return $this->specialhtml ? str_replace(array('&','" ','\'','<','>'),array('&amp;','&quot;',''','&lt;','&gt;'),$value) : $value;}function remove_char($value){$result = $this->removechar == 'manual' ? $this->remove_char_manual($value) : $this->remove_char_auto($value);return str_replace(' ','_',trim($result));}private function remove_char_manual($value){return str_replace(array('&','"','\'','<','>','(',')','%'),'',trim($value));}private function remove_char_auto($str,$x=0){$x==0 ? $str=$this->make_semiangle($str) : '' ; eregi('[[:punct:]]',$str,$arr);$str = str_replace($arr[0],'',$str);return eregi('[[:punct:]]',$str) ? $this->remove_char_auto($str,1) : $str;}private function make_semiangle($str){$arr = array('0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4','5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9','A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E','F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J','K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O','P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T','U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y','Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd','e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i','j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n','o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's','t' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x','y' => 'y', 'z' => 'z','(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[','】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']','‘' => '[', '’' => ']', '{' => '{', '}' => '}', '《' => '<','》' => '>','%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-',':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.',';' => ',', '?' => '?', '!' => '!', '…' => '-', '‖' => '|','”' => '"', '’' => '`', '‘' => '`', '|' => '|', '〃' => '"',' ' => ' ','$'=>'$','@'=>'@','#'=>'#','^'=>'^','&'=>'&','*'=>'*');return strtr($str, $arr);}function __destruct(){fclose($this->handler);}
}
// example:
$csv = new csv_to_array('user.csv');
echo "<pre>"; print_r($csv->get_array()); echo "</pre>";

2. 使用一般函数

<?
function csv_to_array($csv)
{$len = strlen($csv);$table = array();$cur_row = array();$cur_val = "";$state = "first item";for ($i = 0; $i < $len; $i++){//sleep(1000);$ch = substr($csv,$i,1);if ($state == "first item"){if ($ch == '"') $state = "we're quoted hea";elseif ($ch == ",") //empty{$cur_row[] = ""; //done with first one$cur_val = "";$state = "first item";}elseif ($ch == "\n"){$cur_row[] = $cur_val;$table[] = $cur_row;$cur_row = array();$cur_val = "";$state = "first item";}elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";else{$cur_val .= $ch;$state = "gather not quote";}}elseif ($state == "we're quoted hea"){if ($ch == '"') $state = "potential end quote found";else $cur_val .= $ch;}elseif ($state == "potential end quote found"){if ($ch == '"'){$cur_val .= '"';$state = "we're quoted hea";}elseif ($ch == ','){$cur_row[] = $cur_val;$cur_val = "";$state = "first item";}elseif ($ch == "\n"){$cur_row[] = $cur_val;$table[] = $cur_row;$cur_row = array();$cur_val = "";$state = "first item";}elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";else{$cur_val .= $ch;$state = "we're quoted hea";}}elseif ($state == "wait for a line feed, if so close out row!"){if ($ch == "\n"){$cur_row[] = $cur_val;$cur_val = "";$table[] = $cur_row;$cur_row = array();$state = "first item";}else{$cur_row[] = $cur_val;$table[] = $cur_row;$cur_row = array();$cur_val = $ch;$state = "gather not quote";}    }elseif ($state == "gather not quote"){if ($ch == ","){$cur_row[] = $cur_val;$cur_val = "";$state = "first item";}elseif ($ch == "\n"){$cur_row[] = $cur_val;$table[] = $cur_row;$cur_row = array();$cur_val = "";$state = "first item";}elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";else $cur_val .= $ch;}}return $table;
}//pass a csv string, get a php array
// example:
$arr = csv_to_array(file_get_contents('user.csv'));
echo "<pre>"; print_r($arr);   echo "</pre>"

或者

<?
$arrCSV = array();
// Open the CSV
if (($handle = fopen("user.csv", "r")) !==FALSE) {// Set the parent array key to 0$key = 0;// While there is data available loop through unlimited times (0) using separator (,)while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {// Count the total keys in each row$c = count($data);//Populate the arrayfor ($x=0;$x<$c;$x++) $arrCSV[$key][$x] = $data[$x];$key++;} // end while// Close the CSV filefclose($handle);
} // end if
echo "<pre>"; print_r($arrCSV); echo "</pre>";
?>

php csv to array (csv 转数组)相关推荐

  1. node + ts读取csv文件为二维数组

    node + TypeScript读取csv文件为二维数组 CSDN用户名:jcLee95 邮箱:291148484@163.com 原创不易,感谢点赞支持. 在数据分析的时候经常需要读取csv格式的 ...

  2. python读取csv时keyerror_python – 读取csv文件并传输到数组的KeyError

    我无法使用此代码的清理版本重现问题: # Read csv file import csv with open('r2.csv', 'r') as infile: reader = csv.DictR ...

  3. csv解析java_Java CSV解析器

    csv解析java Welcome to the Java CSV Parser tutorial. CSV files are one of the most widely used format ...

  4. php csv 类,php csv操作类代码 - trim

    ...>require (MYSQL);if ($_SERVER['REQUEST_METHOD'] == 'POST') {$trimmed = array_map('trim', $_POS ...

  5. array,vector对象 数组越界检测

    array,vector对象 数组越界检测 posted on 2017-11-15 16:20 秦瑞It行程实录 阅读(...) 评论(...) 编辑 收藏 转载于:https://www.cnbl ...

  6. ML之RF:基于RF算法实现案例(数据集samtrain.csv、samval.csv、samtest.csv)

    ML之RF:基于RF算法实现案例(数据集samtrain.csv.samval.csv.samtest.csv) 目录 输出结果 核心代码 参考 输出结果 核心代码 #我们对训练集采用随机森林模型,并 ...

  7. C++实现array right rotation数组右旋转(附完整源码)

    C++实现array right rotation数组右旋转算法 C++实现array right rotation数组右旋转算法完整源码(定义,实现,main函数测试) C++实现array rig ...

  8. C++实现array left rotation数组左旋转(附完整源码)

    C++实现array left rotation数组左旋转算法 C++实现array left rotation数组左旋转算法完整源码(实现,main函数测试) C++实现array left rot ...

  9. python csv使用_python CSV模块的使用

    简介 CSV(comma separated values),逗号分隔值(字符分割值,字符可以不是逗号),常用的文本格式,用以存储表格数据,包括数字或者字符.kaggle就是csv格式,python有 ...

最新文章

  1. DotNetCore跨平台~System.DrawingCore部署Linux需要注意的
  2. tensorflow object detection API训练错误解决
  3. POJ - 2559 Largest Rectangle in a Histogram(笛卡尔树,单调栈实现)
  4. C++STL总结笔记(二)——仿函数(函数对象)
  5. 去苹果浏览器默认样式
  6. 技术干货 | 应用上线前的“体检”,你知道需要检测哪些指标吗?
  7. ucenter php7.0版,UCenter1.5.0/UCenter Home1.5/Discuz! 7.0
  8. 非常全面的讲解SpringCloud中Zuul网关原理及其配置,看它就够了!
  9. 哲学家都在干些什么_哲学家们都干了些什么——哲学是什么
  10. 8/7排位赛,codeforces501
  11. JAVA8 之 Stream sorted() 示例
  12. Ubuntu下搭建git服务器步骤
  13. 机器学习项目-金融反欺诈模型
  14. lvm 多个硬盘合成一个_linux使用LVM合并硬盘
  15. 数据中台:建立在数据网络效应之上的赛道
  16. BAPI中的货物移动事务代码
  17. QSL建表,建序列,建触发器
  18. OpenGL学习笔记:Bloom 泛光
  19. CSS FIXED porn javhd
  20. 邮票的孔怎么做出来的_邮票怎么做防潮工作,防潮柜有用吗【中华古画古物邮票吧】...

热门文章

  1. 字符三角形(信息学奥赛一本通-T1004)
  2. 信息学奥赛一本通C++语言——1105:数组逆序重存放
  3. 信息学奥赛一本通C++语言——1008:计算(a+b)/c的值
  4. 安卓系统分屏相关修改思路
  5. C语言 strlen函数实现
  6. 无法启动程序因为计算机中丢失礼包,Win10开机提示“计算机中丢失mfc110u.dll”的解决方法...
  7. 最大子数组下标java,【算法】最大子数组
  8. scatter python_Python scatter详解
  9. OpenGL:glMatrixMode()
  10. 笨方法“学习python笔记之条件控制