我正在尝试导入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
您可以设置一个包含要显示的列的数组(在我的前任 1 和 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
?>
尝试:
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 块中的索引来完成的。
这是一篇旧帖子,但我找到了另一种可以帮助某人的方法:
$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;
}