【问题标题】:Make a multi-column table from a CSV file using PHP使用 PHP 从 CSV 文件创建多列表
【发布时间】:2017-01-01 05:00:15
【问题描述】:

我正在尝试使用 PHP 从 CSV 文件创建多列表。我希望表格单元格垂直列出。例如,如果我有一个 CSV 文件,其名称为:

bill
mike
sarah
steve
kim
dave

假设我需要 2 列,我希望表格像这样垂直列出:

bill   steve     
mike   kim   
sarah  dave

我不希望表格水平列出,如下所示:

bill   mike     
sarah  steve   
kim    dave

我使用以下代码从包含球员姓名、球队名称的 CSV 文件制作了一个单列表格 - 我还传入了球队位置属性。我希望能够将列垂直拆分为 3 列。代码如下:

<?PHP

$file_handle = fopen("CSV Team Example.csv", "r");

echo "<table border = '0' cellspacing='1' cellpadding='3'>\n";

while (!feof($file_handle) ) {

$line_of_text = fgetcsv($file_handle);

echo "<tr>\n<td width = '200' position = '" . $line_of_text[2] . "'>". $line_of_text[0]. "  <br> &nbsp;" . $line_of_text[1] . "</td>\n</tr>\n";

}

fclose($file_handle);

echo "</table>";

?>

这是我正在使用的 CSV 文件。非常感谢您的考虑。

CSV 文件:

Scott L. Aranda,Red Devils,Offense
Todd D. Smith,Blue Streaks,Offense
Edward M. Grass,Red Devils,Defense
Aaron G. Frantz,Blue Streaks,Defense
Ryan V. Turner,Red Devils,Offense
Belinda J. Bridges,Red Devils,Defense
Raymond P. Webb,Blue Streaks,Offense
Allison M. Elwell,Blue Streaks,Defense
Melinda B. Savino,Blue Streaks,Offense
Wendy R. Lane,Red Devils,Offense
Gordon Q. Farmer,Blue Streaks,Defense
William F. Lawrence,Red Devils,Offense
Christa L. Limones,Blue Streaks,Offense
Sandra C. Singleton,Red Devils,Offense
Keshia M. Garcia,Blue Streaks,Defense
Margaret A. Arnold,Red Devils,Defense
Paul S. Gonzalez,Blue Streaks,Offense
Mark V. Stocks,Red Devils,Defense
Elizabeth J. Quinn,Red Devils,Offense
Rusty M. Collette,Red Devils,Offense
Myra L. Armstrong,Blue Streaks,Defense
William B. Stewart,Blue Streaks,Defense
Erin J. Hoch,Red Devils,Defense
Robin S. Meredith,Blue Streaks,Offense
Sherie D. Lee,Red Devils,Offense
Michael A. Whitney,Blue Streaks,Defense
Louis R. Ochoa,Red Devils,Defense
Paul R. Garcia,Blue Streaks,Offense
Chester A. Bailey,Red Devils,Defense
Johnny B. Coover,Red Devils,Defense
Emily K. Wright,Red Devils,Offense
Perry D. Desmarais,Red Devils,Offense
Judie J. Burns,Blue Streaks,Defense
Martin L. Dunn,Blue Streaks,Defense
Stephanie C. Rose,Blue Streaks,Defense
Don T. Grimes,Blue Streaks,Offense
Robert C. Devito,Blue Streaks,Offense
Michael J. Taylor,Red Devils,Defense
Melissa D. Bush,Red Devils,Offense

【问题讨论】:

    标签: php csv html-table


    【解决方案1】:

    首先将整个文件读入一个项目数组,然后将该数组拆分为 X 个部分(其中 X 是您想要的列数),然后将每个部分中的一个项目输出到一行中,对每一行重复。

    您当前在从文件中读取时在同一个循环中输出的方法不适用于您尝试将其分解的方式,因为您不知道第 2 列中的第一项将是什么,直到您'已经看过所有的项目。

    【讨论】:

      【解决方案2】:

      对不起,我误解了这个问题。

      $csv = 'bill,mike,sarah,steve,kim,dave';
      $csv = str_getcsv(implode(',', explode("\n", trim($csv))), ',', '');
      $columns = 2;
      
      echo '<table border="1" cellspacing="1" cellpadding="3">';
      
      for ($i = 0; $i < count($csv) / $columns; $i++)
      {
          echo '<tr>';
      
          for ($j = 0; $j < $columns; $j++)
          {
              echo '<td width="200">' . $csv[$i + ($j * ($columns + 1))] . '</td>';
          }
      
          echo '</tr>';
      }
      
      echo '</table>';
      

      返回:

      bill    steve
      mike    kim
      sarah   dave
      

      【讨论】:

        【解决方案3】:

        看下面的伪代码,在php中使用mod操作符可以避免拆分和复制数组。

        编辑:忘记初始化 $numcols 变量!!应该适用于任意数量的

        echo '<table>';
        $f = file('..');
        $numcols = 2;
        for($i=0;$i<count($f);$i++)
        {
        $data = str_getcsv($f[$i]);
        if($i % $numcols == 0) echo '<tr>';
        
        // cell diplay here..
        echo '<td>' . $data[???] . '</td>';
        
        if($i+1 < count($f) && ($i+1 % $numcols) == 0) echo '</tr>';
        }
        
        echo '</table>';
        

        或它的变体。

        【讨论】:

          【解决方案4】:

          非常感谢大家的帮助。我设法通过按照上面 Dav 的建议创建一个数组来完成这项工作。代码有点难看,但它可以完成工作 - 我几乎是一个 php 新手,我从网上找到的示例中整理了这些。

          最后一个问题,我正在使用explode 函数根据逗号分隔CSV 文件。如果我的一个字段有多个逗号,我担心这将不起作用,例如地址:123 elm street, bethesda, maryland 20816。我更喜欢在创建数组时使用 fgetcsv,但我不确定怎么做。有人可以帮我吗?

          此外,我的托管服务上的 php 版本似乎不支持 str_getcsv,因此它对我不起作用。

          这是我迄今为止使用的代码 - 它根据我的简单 CSV 文件为我提供了完美的结果,我将在下面再次发布。

          代码:

          <?PHP
          // set the number of columns you want
          $columns = 4;
          
          // count up number of lines in your CSV file
          $file_handle = fopen("CSV Team Example.csv", "r");
          $row = 0;
          while (!feof($file_handle) ) {
          $line_of_text = fgetcsv($file_handle, 1024);
          $row++;
          }
          $number_of_rows = $row;
          fclose($file_handle);
          
          // calculate number of rows per column
          $rows_per_column = ceil($number_of_rows / $columns);
          
          // create your array
          $lines =file('CSV Team Example.csv');
          
          foreach($lines as $data)
          {
          list($name[],$team[],$team_position[])
          = explode(',',$data);
          }
          
          // make your table
          echo "<TABLE BORDER=\"0\">\n";
          
          //here we changed the condition to $i < $rows_per_column
          for($i = 0; $i < $rows_per_column; $i++) {
          
              echo "<TR>\n";
          
              //here will run another loop for the amount of columns
              for($j = 0; $j < $columns; $j++) {
                  echo "<td width = '200' position = '" . $team_position[$i + ($j * $rows_per_column)]  . "'>". $name[$i + ($j * $rows_per_column)] . "  <br> &nbsp;" . $team  [$i + ($j * $rows_per_column)] . "</td>\n";
                  }
              echo "</TR>\n";
          }
          echo "</TABLE>\n";
          ?>
          

          这是我的 CSV 文件:CSV Team Example.csv。第一列是球员姓名,第二列是球队名称,第三列是他们的位置。

          Scott L. Aranda,Red Devils,Offense
          Todd D. Smith,Blue Streaks,Offense
          Edward M. Grass,Red Devils,Defense
          Aaron G. Frantz,Blue Streaks,Defense
          Ryan V. Turner,Red Devils,Offense
          Belinda J. Bridges,Red Devils,Defense
          Raymond P. Webb,Blue Streaks,Offense
          Allison M. Elwell,Blue Streaks,Defense
          Melinda B. Savino,Blue Streaks,Offense
          Wendy R. Lane,Red Devils,Offense
          Gordon Q. Farmer,Blue Streaks,Defense
          William F. Lawrence,Red Devils,Offense
          Christa L. Limones,Blue Streaks,Offense
          Sandra C. Singleton,Red Devils,Offense
          Keshia M. Garcia,Blue Streaks,Defense
          Margaret A. Arnold,Red Devils,Defense
          Paul S. Gonzalez,Blue Streaks,Offense
          Mark V. Stocks,Red Devils,Defense
          Elizabeth J. Quinn,Red Devils,Offense
          Rusty M. Collette,Red Devils,Offense
          Myra L. Armstrong,Blue Streaks,Defense
          William B. Stewart,Blue Streaks,Defense
          Erin J. Hoch,Red Devils,Defense
          Robin S. Meredith,Blue Streaks,Offense
          Sherie D. Lee,Red Devils,Offense
          Michael A. Whitney,Blue Streaks,Defense
          Louis R. Ochoa,Red Devils,Defense
          Paul R. Garcia,Blue Streaks,Offense
          Chester A. Bailey,Red Devils,Defense
          Johnny B. Coover,Red Devils,Defense
          Emily K. Wright,Red Devils,Offense
          Perry D. Desmarais,Red Devils,Offense
          Judie J. Burns,Blue Streaks,Defense
          Martin L. Dunn,Blue Streaks,Defense
          Stephanie C. Rose,Blue Streaks,Defense
          Don T. Grimes,Blue Streaks,Offense
          Robert C. Devito,Blue Streaks,Offense
          Michael J. Taylor,Red Devils,Defense
          Melissa D. Bush,Red Devils,Offense
          

          【讨论】:

            【解决方案5】:

            好的,让它只与 fgetcsv 一起工作 - 没有使用“爆炸”功能。谢谢大家。

            <?PHP
            $columns = 4;
            
            $file = fopen('CSV Team Example.csv', 'r');
            $row = 0;
            while (($line = fgetcsv($file)) !== FALSE) 
            {  
            //$line is an array of the csv elements  
            list($name[], $team[], $team_position[]) = $line;
            $row++;
            }
            $number_of_rows = $row;
            fclose($file);
            
            // calculate number of rows per column
            $rows_per_column = ceil($number_of_rows / $columns);
            // make your table
            echo "<TABLE BORDER=\"0\">\n";
            
            //here we changed the condition to $i < $rows
            for($i = 0; $i < $rows_per_column; $i++) {
            
            echo "<TR>\n";
            
            //here will run another loop for the amount of columns
            for($j = 0; $j < $columns; $j++) {
                echo "<td width = '200' position = '" . $team_position[$i + ($j * $rows_per_column)]  . "'>". $name[$i + ($j * $rows_per_column)] . "  <br> &nbsp;" . $team[$i + ($j * $rows_per_column)] . "</td>\n";
                }
            echo "</TR>\n";
            }
            echo "</TABLE>\n";
            ?>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-05-06
              • 2017-01-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-12-06
              相关资源
              最近更新 更多