0

我有一个读取 CSV 文件的脚本。

 <?php
 echo '<table border="0" cellspacing="1" cellpadding="1" class="sortable" border="1"><caption>Title Here</caption>
 <thead><tr><th class="header">Time:</th><th class="header">Value 1:</th><th class="header">Value 2:</th><th class="header">Value 3:</td class="header"><th class="header">Value 4:</th><th class="header">Value 5:</th><th class="header">Value 6:</th><th class="header">Value 7:</th><th class="header">Value 8:</th><th class="header">Value 9:</th></tr></thead><tbody><tr>';
 $row = 1;
 if (($handle = fopen("data.csv", "r")) !== FALSE) {
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
     $num = count($data);   
     $row++;
     for ($c=0; $c < $num; $c++) {
        if ($c==9) { echo "<td>".$data[$c] ."</td></tr><tr>";}
        else  {echo "<td>".$data[$c] ."</td>"; }
     }
   }
   fclose($handle);
 }
 echo '</tbody></table>';
 ?>

该脚本只是获取数据并将它们打印在 html 表中。我只想重新排列表格。例如 csv 可能有这些内容

0 1 2 3 4 5 6 7

0 1 2 3 4 5 6 7

0 1 2 3 4 5 6 7

0 1 2 3 4 5 6 7

我希望结果是:

0 0 0 0

1 1 1 1

2 2 2 2

3 3 3 3

4 4 4 4

继续...我有些我必须添加一个额外的循环..我该怎么做?

4

2 回答 2

0

我不确定您的 csv 文件的布局方式,但看起来您可能需要将这些值存储在不同数字的单独数组中,然后在完成读取整个 csv 文件后循环遍历这些数组。您能否展示一个 csv 文件的简短示例,以便我了解您正在读取的数据?

于 2010-08-03T20:49:10.117 回答
0

好吧,您会将 CSV 文件读入多维数组。

考虑到 CSV 文件中的每一行现在都是一列(从上到下而不是从左到右)。这称为将行转换为列。

对于表格,您需要遍历每一行,而不是每一列。因此,您在循环中创建一个循环,如下所示:

<table border="0" cellspacing="1" cellpadding="1" class="sortable" border="1"><caption>Title Here</caption>
     <thead><tr><th class="header">Time:</th><th class="header">Value 1:</th><th class="header">Value 2:</th><th class="header">Value 3:</td class="header"><th class="header">Value 4:</th><th class="header">Value 5:</th><th class="header">Value 6:</th><th class="header">Value 7:</th><th class="header">Value 8:</th><th class="header">Value 9:</th></tr></thead><tbody>
<?php
     #read CSV file
     if (($handle = fopen("data.csv", "r")) !== FALSE) {
       $mycsv = array();
       while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) $mycsv[] = $data;
       fclose($handle);


     #Find the length of the transposed row

     $row_length = count($mycsv);

     #Loop through each row (or each line in the csv) and output all the columns for that row
     foreach($mycsv[0] as $col_num => $col)
     {
        echo "<tr>";
        for($x=0; $x<$row_length; $x++)
           echo "<td>".$mycsv[$x][$col_num]."</td>";


        echo "</tr>";
     }

  }
?>
  </tbody></table>

试试看,让我知道它是否有效。

于 2010-08-05T06:06:53.147 回答