[英]How to read a CSV file into a 2d Array PHP
我正在尝试将csv文件读入数组。 到目前为止,这是我将csv读入数组的结果:
$i = 0;
while ($i < $fileLines) {
$userDB=Array(
($i) => Array
(
(title) => $harry[$i][0],
(subtitle) => $harry[$i][1],
(series) => $harry[$i][2],
(author) => $harry[$i][3],
(author2) => $harry[$i][4],
(author3) => $harry[$i][5],
(category) => $harry[$i][6],
(subjects) => $harry[$i][7],
(callnumber) => $harry[$i][8],
(isbn) => $harry[$i][9],
(publisher) => $harry[$i][10],
(keywords) => $harry[$i][11],
(option1) => $harry[$i][12],
(option2) => $harry[$i][13],
(option3) => $harry[$i][14],
(option4) => $harry[$i][15],
(option5) => $harry[$i][16],
(option6) => $harry[$i][17]
) // end child array
); // end parent array
$i++;
} // end while
这是我正在使用的CVS的示例:
"Algebra and Trigonometry with Analytic Geometry, Classic Edition",,,"Swokowski, Earl","Cole, Jeffery A.",,Cengage Learning,,,495559717,,,,," ALGEBRA AND TRIGONOMETRY WITH ANALYTIC GEOMETRY, CLASSIC EDITION 12 SWOKOWSKI, EARL COLE, JEFFERY A. CENGAGE LEARNING 2009-01-28 912 500 0495559717 "
All My Friends Are Dead,,,"Monsen, Avery","John, Jory",,Chronicle Books,,,811874559,,,,," ALL MY FRIENDS ARE DEAD MONSEN, AVERY JOHN, JORY CHRONICLE BOOKS 2010-06-30 96 500 0811874559 "
All My Friends Are Still Dead,,,"John, Jory","Monsen, Avery",,Chronicle Books,,,1452106967,,,,," ALL MY FRIENDS ARE STILL DEAD 3.2.2012 JOHN, JORY MONSEN, AVERY CHRONICLE BOOKS 2012-03-07 108 500 1452106967 "
当我尝试遍历写入数组时出现问题。 如果我注释了while循环,那么我会正确读取CSV中的第一项。 但是,当我尝试使用while循环时,则不会将任何数据写入数组。 我缺少什么/做错了什么?
我没有包含所有代码,因为我不想淹没所有人,但是如果有帮助,我可以添加更多代码。
您必须在while循环之前声明$userDB
:
$i = 0;
$userDB = array();
while ($i < $fileLines) {
$userDB[] => Array
(
(title) => $harry[$i][0],
(subtitle) => $harry[$i][1],
(series) => $harry[$i][2],
(author) => $harry[$i][3],
(author2) => $harry[$i][4],
(author3) => $harry[$i][5],
(category) => $harry[$i][6],
(subjects) => $harry[$i][7],
(callnumber) => $harry[$i][8],
(isbn) => $harry[$i][9],
(publisher) => $harry[$i][10],
(keywords) => $harry[$i][11],
(option1) => $harry[$i][12],
(option2) => $harry[$i][13],
(option3) => $harry[$i][14],
(option4) => $harry[$i][15],
(option5) => $harry[$i][16],
(option6) => $harry[$i][17]
) // end child array
); // end parent array
$i++;
} // end while
顺便说一句,为什么不直接使用fgetcsv或str_getcsv php函数?
$userDB = str_getcsv($fileLines);
我用这种方法:
$formattedArr = array(); // create array
$filename = "sample.csv"; // point to CSV file
if (($handle = fopen($filename, "r")) !== FALSE) {
$key = 0; // set array key.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$count = count($data); //get total keys in row
for ($i=0; $i < $count; $i++) { //insert data to our array
$formattedArr[$key][$i] = $data[$i];
} // end for
$key++;
} // end while
fclose($handle); //close file handle
} // end if
它通过CSV运行,并将每个项目添加到一个位置(例如$ formattedArr [0] [0] =“带解析几何的代数和三角学,经典版”。感谢您的评论,建议和答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.