我有一个PHP脚本,可以从CSV文件生成HTML表格。
现在,如果任何单元格缺少信息,它会跳过该行。但是,如果缺少一个以上的单元格,我更喜欢它会跳过一行。 因此,如果一行有2个空单元格,则应跳过。
我已将其标记为//edit here
,但不确定如何实现此目标。
<?php
$idsColumnsWanted = array(0,1,8,19);
echo "<table class='table table-bordered' id='example'>\n\n";
$f = fopen("users.csv", "r");
$first_line = false;
while (($line = fgetcsv($f)) !== false) {
// Restart column index
$i = 0;
$row ="";
if($first_line == false) {
$row = "<thead><tr>";
$col = "th";
} else {
$row = "<tr>";
$col= "td";
}
$is_empty = false;
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted)) continue;
// edit here
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$is_empty = true;
}
// Increase index
$i++;
}
if($first_line == false)
$row .= "</tr></thead>";
else
$row .= "</tr>";
$first_line = true;
if ($is_empty) {
continue;
} else {
echo $row;
}
}
fclose($f);
echo "\n</table>";
?>
答案 0 :(得分:2)
请尝试此代码
$is_empty = false;
$count = 0;
$countlimit = 2; // define empty cell limit here
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (!in_array($i, $idsColumnsWanted))
continue;
// edit here
if($cell==""){
$count++;
}
if ($count <= $countlimit) {
$row .= "<" . $col . ">" . htmlspecialchars($cell) . " </" . $col . ">";
} else {
$is_empty = true;
break;
}
}
答案 1 :(得分:1)
你必须连续多少个单元格是空的。为此,请为每一行启动计数器。
$empty_cells = 0; //Init with 0 for each line
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted)) continue;
// edit here
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$empty_cells++; //count how many empty cells you have.
}
// Increase index
$i++;
}
然后检查是否有两个以上的空单元格:
if ($empty_cells >= 2) {
continue;
} else {
echo $row;
}