[英]PHP parse CSV by columns
我想寻求有关此任务的帮助:例如,我有CSV格式:
column1$column2$column3
123$xyz$321
456$zyx$654
我想通过PHP将其解析为按列/标题的数组-例如
$column1 = {123,456}
$column2 = {xyz,zyx}
$column3 = {321,654}
感谢大家。
考虑以下代码和说明:
$file = file("example.csv"); // read the file to an array
$cols = array();
for ($i=1;$i<count($file);$i++) { // loop over $file,
// starting in the second line
$row = explode('$', $file[$i]); // make an array with explode
for ($j=0;$j<count($row);$j++) // loop over the $row array
array_push($cols["column".$j], $row[$j]);
// push it to the cols array
}
print_r($cols);
你的大括号应该做什么? 在PHP中,数组由[]
。
与其将整个文件读取到一个数组中,还可以读取每一行并将其推入cols数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.