質問

I'm using the code below (from a previous post) to pull from an csv file but I'd like to just display specific columns. I've already tried to modify using other solutions with no avail. Any help would be much appriciated.

<?php 
function jj_readcsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo '<table width="400" border="1" bordercolor="#666666" cellspacing="0" cellpadding="2">';
//display header row if true
if ($header) {
    $csvcontents = fgetcsv($handle);
    echo '<tr>';
    foreach ($csvcontents as $headercolumn) {
    echo "<th>$headercolumn</th>";
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
    echo '<tr>';
    foreach ($csvcontents as $column) {
       echo "<td>$column</td>";
    }
    echo '</tr>';
}
echo '</table>';
fclose($handle);
}
?>

HEADER1 | HEADER2 | HEADER3
COLUMN1 | COLUMN2 | COLUMN3
COLUMN1 | COLUMN3 | COLUMN3

Summary: I just want to display 1&2

役に立ちましたか?

解決

Assuming you dont want to display the second column, iterate through the numerically indexed array and exclude the ones you want, something like:

  <?php 
  function jj_readcsv($filename, $header=false) {
  $handle = fopen($filename, "r");
  echo '<table width="400" border="1" bordercolor="#666666" cellspacing="0" cellpadding="2">';
  //display header row if true
 if ($header) {
  $csvcontents = fgetcsv($handle);
  echo '<tr>';
  foreach ($csvcontents as $k => $v) {
    if ($k != 1) {
        echo "<th>$vth>";
    }
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $k => $v) {
   if ($k != 1) {
        echo "<td>$v</td>";
    }
}
echo '</tr>';
}
echo '</table>';
fclose($handle);
}
?>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top