使用PHP隐藏CSV中的某些表列

时间:2016-09-04 06:57:54

标签: php html csv

我正在使用以下代码从CSV文件生成HTML表格。

我只想显示包含以下索引的列:

$idsColumnsWanted = array(0,1,19,16);

如何将其用于现有代码?

echo "<table class='table table-bordered'>\n\n";

$f = fopen("users.csv", "r");

$first_line=false;

while (($line = fgetcsv($f)) !== false) {
    $row ="";

    if($first_line == false) {
         $row = "<thead><tr>";
         $col= "th";
    }
    else {
         $row = "<tr>";
         $col= "td";
    }


    $is_empty = false;

    foreach ($line as $cell) {
        if ($cell !== '') {
            $row .= "<".$col.">" . htmlspecialchars($cell) . "</".$col.">";
        } else {
            $is_empty = true;
        }
    }


    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>";

2 个答案:

答案 0 :(得分:1)

您可以尝试使用in_array()函数,并在循环中添加索引$ i:

$idsColumnsWanted = array(0,1,19,16);

echo "<table class='table table-bordered'>\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 $cell) {

        // Skips all columns not in your list
        if (! in_array($i, $idsColumnsWanted) continue;

        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>";

答案 1 :(得分:1)

一种可能的解决方案是将代码更改为:

$idsColumnsWanted = array(0,1,19,16);
for($i=0;$i<count($line);$i++) {
    if (in_array($i, $idsColumnsWanted)) {
        if ($cell !== '') {
            $row .= "<".$col.">" . htmlspecialchars($cell) . "</".$col.">";
        } else {
            $is_empty = true;
        }
    }
}