【问题标题】:Hide certain table columns from CSV with PHP使用 PHP 隐藏 CSV 中的某些表列
【发布时间】:2016-09-04 06:57:53
【问题描述】:

我正在使用以下代码从 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>";

【问题讨论】:

    标签: php html csv


    【解决方案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>";
    

    【讨论】:

      【解决方案2】:

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

      $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;
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-11
        • 2019-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-01
        • 1970-01-01
        相关资源
        最近更新 更多