2016-09-04 4 views
1

Ich erstelle eine HTML-Tabelle aus einer CSV-Datei mit dem folgenden Code.Bestimmte Tabellenspalten aus CSV mit PHP ausblenden

Ich möchte nur auf Spalten mit den folgenden Indizes an:

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

Wie arbeite ich dies in meinem vorhandenen Code?

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

Antwort

1

Sie können mit in_array versuchen() Funktion, und das Hinzufügen eines Index $ i zu Ihrem Zyklus:

$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

Du hast recht @ Jan, meine Schuld. Ich korrigiere – Blazeag

1

Eine mögliche Lösung wäre, um Ihren Code zu ändern:

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