2016-09-04 2 views
1

다음 코드를 사용하여 CSV 파일에서 HTML 테이블을 생성 중입니다.PHP가 포함 된 CSV에서 특정 테이블 열 숨기기

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) { 
    $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>"; 

답변

1

당신이와 in_array() 함수를 시도하고주기에 $ 내가 인덱스를 추가 할 수 있습니다

$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

니가 맞아 .Jan, 내 잘못이야. 나는 고치고있다. – Blazeag

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