首頁  >  文章  >  後端開發  >  php csv to array(csv 轉數組)方法與程式碼

php csv to array(csv 轉數組)方法與程式碼

WBOY
WBOY原創
2016-07-25 08:59:391514瀏覽
  1. //ini_set('memory_limit', '-1'); // 如果csv比較大的話,可以加。
  2. /*
  3. * $file : csv file
  4. * $csvDataArr : header of csv table, eg: arary('name','sex','age') or array(0,1,2)
  5. * $specialhtml : whether do you want to convert special characters to html entities ?
  6. * $removechar : which type do you want to remove special characters in array keys, manual or automatical ?
  7. * edit http://bbs.it-home.org
  8. */
  9. class csv_to_array
  10. {
  11. private $counter;
  12. private $handler;
  13. private $length;
  14. private $file;
  15. private $seprator;
  16. private $specialhtml;
  17. private $removechar = 'manual';
  18. private $csvDataArr;
  19. private $csvData = array();
  20. function __construct($file = '', $csvDataArr = '', $specialhtml = true, $length = 1000, $seprator = ',')
  21. {
  22. $this->counter = 0;
  23. $this->length = $length;
  24. $this->file = $file;
  25. $this->seprator = $seprator;
  26. $this->specialhtml = $specialhtml;
  27. $this->csvDataArr = is_array($csvDataArr) ? $csvDataArr : array();
  28. $this->handler = fopen($this->file, "r");
  29. }
  30. function get_array()
  31. {
  32. $getCsvArr = array();
  33. $csvDataArr = array();
  34. while(($data = fgetcsv($this->handler, $this->length, $this->seprator)) != FALSE)
  35. {
  36. $num = count($data);
  37. $getCsvArr[$this->counter] = $data;
  38. $this->counter++;
  39. }
  40. if(count($getCsvArr) > 0)
  41. {
  42. $csvDataArr = array_shift($getCsvArr);
  43. if($this->csvDataArr) $csvDataArr = $this->csvDataArr;
  44. $counter = 0;
  45. foreach($getCsvArr as $csvValue)
  46. {
  47. $totalRec = count($csvValue);
  48. for($i = 0; $i < $totalRec ; $i++)
  49. {
  50. $key = $this->csvDataArr ? $csvDataArr[$i] : $this->remove_char($csvDataArr[$i]);
  51. if($csvValue[$i]) $this->csvData[$counter][$key] = $this->put_special_char($csvValue[$i]);
  52. }
  53. $counter++;
  54. }
  55. }
  56. return $this->csvData;
  57. }
  58. function put_special_char($value)
  59. {
  60. return $this->specialhtml ? str_replace(array('&','" ','\'','<','>'),array('&','"',''','<','>'),$value) : $value;
  61. }
  62. function remove_char($value)
  63. {
  64. $result = $this->removechar == 'manual' ? $this->remove_char_manual($value) : $this->remove_char_auto($value);
  65. return str_replace(' ','_',trim($result));
  66. }
  67. private function remove_char_manual($value)
  68. {
  69. return str_replace(array('&','"','\'','<','>','(',')','%'),'',trim($value));
  70. }
  71. private function remove_char_auto($str,$x=0)
  72. {
  73. $x==0 ? $str=$this->make_semiangle($str) : '' ;
  74. eregi('[[:punct:]]',$str,$arr);
  75. $str = str_replace($arr[0],'',$str);
  76. return eregi('[[:punct:]]',$str) ? $this->remove_char_auto($str,1) : $str;
  77. }
  78. private function make_semiangle($str)
  79. {
  80. $arr = array('0' => '0', '1' => '1', '2' => ; ' 2', '3' => '4',
  81. '5', '6' => '6', '7' ' => '7', '8' => '8', '9' => 'A' => 'B', 'C' => 'D', 'E' => 'E',
  82. 'F', 'G' => 'G', 'H' => 'I', 'J' => 'J',
  83. 'K', 'L' => 'L', 'M' => 'N', 'O' => 'O',
  84. 'P', 'Q' => 'R', 'S' => 'T',
  85. 'U' => 'U', 'V' => 'V', 'W' => 'X ', 'Y' => 'Y',
  86. 'Z' => 'Z', 'a' => 'b', 'c' => 'c', 'd' => 'e' = > 'f' => 'g', 'h' => 'i',
  87. 'j', 'k' => 'l', 'm' => ',
  88. 'o' = > ; 'o', 'p' => 'p', 'q' =>; 'q', 'r' => 'r', 's' => 's',
  89. 't' = > ; 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
  90. 'y' => ; 'y', 'z' => 'z',
  91. '(' =>; '(', ')' => ')', '〔' => '[', ']' => ' ]', '【' => '[',
  92. '】' => ']', '〖' => '[', '〗' => ']', '"' => '[ ' , '"' => ']',
  93. ''' => '[', ''' => ']', '{' => '{', '}' => '}'; , '《' => ' '》' => '>',
  94. '%' =>; '%', '+' => '+', '—' => ' - ', '-' => '-', '~' => '-',
  95. ':' =>; ':', '。 , ',' => '.', '、' => '.',
  96. ';' => ',', '? ' => '?', '! ...' => '-', '``' => '|',
  97. '"' => '"', ''' => '`', ''' => '`' , '|' => '|', '〃' => '"',
  98. '' => ' ','$'=>'$','@'=>'@','#' = >'#','^'=>'^','&'=>'&','*'=>'*');
  99. return strtr($str, $arr);
  100. }
  101. function __destruct(){
  102. fclose($this->handler);
  103. }
  104. }
  105. // 範例:
  106. $csv = new csv_to_array('user.csv');
  107. echo "
    "; print_r($csv->get_array());迴聲「
    」;
  108. ?>
複製程式碼

2、使用一般函數

  1. 函數csv_to_array($csv)
  2. {
  3. $len = strlen($csv);
  4. $table = array();
  5. $cur_row = array() ;
  6. $cur_val = "";
  7. $state = "第一項";
  8. for ($i = 0; $i {
  9. //sleep(1000);
  10. $ch = substr($csv,$i,1);
  11. if ($state == "第一項")
  12. {
  13. if ($ch == '"') $state = "我們被引用了hea";
  14. elseif ($ch = = ",") //空
  15. {
  16. $cur_row[] = " "; //完成第一個
  17. $cur_val = ""; $state = "第一項"
  18. }
  19. elseif ($ch == "n")
  20. {
  21. $ cur_row[] = $cur_val;
  22. $table[] = $cur_row
  23. $cur_row = array( );
  24. $cur_val = "";
  25. $state = "第一項"
  26. }
  27. elseif ($ch == "r") $state = "等待換行,如果所以關閉行! ";
  28. else
  29. {
  30. $cur_val .= $ch;
  31. $state = "收集而不引用";
  32. }
  33. }
  34. elseif ($state == "我們被引用了hea")
  35. {
  36. if ($ch == '"') $state = "找到潛在的結束引用";
  37. else $cur_val .= $ch;
  38. }
  39. elseif ($state == "找到潛在的結束引用")
  40. {
  41. if ($ch == '"')
  42. {
  43. $cur_val .= '" ';
  44. $state = "我們被引用了";
  45. }
  46. elseif ($ch == ',')
  47. {
  48. $cur_row[] = $cur_val ;
  49. $cur_val = "";
  50. $state = "第一項";
  51. }
  52. elseif ($ch == "n")
  53. {
  54. $cur_row[] = $cur_val;
  55. $table[] = $cur_row;
  56. $cur_row = array();
  57. $cur_val = "";
  58. $state = "第一項";
  59. }
  60. elseif ($ch == "r") $state = "等待換行,如果這樣就關閉行!";
  61. else
  62. {
  63. $cur_val .= $ch;
  64. $ state = "我們被引用了";
  65. }
  66. }
  67. elseif ($state == "等待換行,如果這樣就關閉行!")
  68. {
  69. if ( $ch == "n ")
  70. {
  71. $cur_row[] = $cur_val;
  72. $cur_val = "";
  73. $table[] = $cur_row;
  74. $cur_row = array ();
  75. $state = "第一項";
  76. }
  77. else
  78. {
  79. $cur_row[] = $cur_val;
  80. $table[] = $ cur_row;
  81. $cur_row = array();
  82. $cur_val = $ch;
  83. $state = "收集而不引用";
  84. }
  85. }
  86. elseif ( $state == "收集而不引用")
  87. {
  88. if ($ch == ",")
  89. {
  90. $cur_row[] = $cur_val;
  91. $cur_val = " ";
  92. $state = "第一項";
  93. }
  94. elseif ($ch == "n")
  95. {
  96. $cur_row[] = $cur_val;
  97. $table[] = $cur_row;
  98. $cur_row = array();
  99. $cur_val = "";
  100. $state = "第一項";
  101. }
  102. elseif ( $ch == "r") $state = "等待換行,如果這樣就關閉行! ";
  103. else $cur_val .= $ch;
  104. }
  105. }
  106. 回傳 $table;
  107. }
  108. //傳遞一個csv字串,得到一個php陣列
  109. // 範例:
  110. $arr = csv_to_array(file_get_contents('user.csv'));
  111. echo "
    "; print_r($arr); 回顯“
  112. ? >
複製程式碼

  1. $arrCSV = array();
  2. // 開啟CSV
  3. if (($handle = fopen("user.csv", "r")) !==FALSE) {
  4. //將父數組鍵設為0
  5. $key = 0;
  6. // 當有資料可用時,使用分隔符號(,) 無限次循環(0)
  7. while (($data = fgetcsv($ handle, 0, ",")) !==FALSE) {
  8. // 統計每行的鍵總數
  9. $c = count($data);
  10. //填入陣列
  11. for ( $x=0;$x $key++;
  12. } // 結束while
  13. / / 關閉CSV 檔案
  14. fclose($handle);
  15. } // 結束if
  16. echo "
    "; print_r($arrCSV);迴聲「
    」;
  17. ?>
複製程式碼

至於哪種工作用,看自己的實際需求與個人愛好了,實際中csv轉數組的需求還是很旺,建議大家多練習,多掌握。



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn