我正在尝试导入CSV,并且能够删除列,并且只能导入选定的列。
因此,我有一个由选定字段和CSV文件组成的数组。我可以删除行,但在跳过列时遇到问题。
下面是我用来显示表的内容,只是尝试删除列。这里没什么特别的。只需要知道在哪里放置任何if语句,或任何东西。小贴士,建议,样品都欢迎!
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
echo("\t<td>$val</td>\r\n");
}
echo("</tr>\r\n");
} //end while我应该把只允许剩余行的if语句放在哪里?我试过in_array,array_diff等--似乎什么都不起作用?
现在我已经输入了这段代码,我是否应该在插入之前使用PHP删除这些列?最佳实践是什么?
谢谢jt
发布于 2012-06-10 08:35:29
您可以设置一个包含要显示的列的数组(在我的ex1和3中),并使用foreach的关键部分来了解您正在扫描的列:
<?
$handle = fopen("test.csv", "r");
$columns = array(1,3);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
if (in_array($index+1, $columns)) {
echo("\t<td>$val</td>\r\n");
}
}
echo("</tr>\r\n");
} //end while
?>发布于 2012-06-10 08:30:52
尝试:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
if($index != BADINDEX) {
echo("\t<td>$val</td>\r\n");
}
}
echo("</tr>\r\n");
}其中,BADINDEX是要删除的列号(第一列为0)。
因为从fgetcsv得到的是行而不是列,所以只需要为打印的每一行过滤出所需的列,这是通过检查foreach块中的索引来完成的。
发布于 2017-09-26 07:15:07
这是一个古老的帖子,但我发现了另一种可能对某人有帮助的方法:
$file = fopen($yourcsvfile, 'r');
while (($result = fgetcsv($file, 1000, ",")) !== false)
{
$temp = array();
$temp[] = $result[1]; // the column you want in your new array
$temp[] = $result[2]; // the column you want in your new array
$csv1[] = $temp;
}https://stackoverflow.com/questions/10965436
复制相似问题