【问题标题】:Sort CSV file and display in HTML table with PHP使用 PHP 对 CSV 文件进行排序并显示在 HTML 表格中
【发布时间】:2016-02-24 22:50:42
【问题描述】:

我有一个包含如下(虚拟)数据的 CSV 文件:

Mike Judge, Office Space, Comedy
Larry Wachowski, Matrix Zero, Action
Sofia Coppola, Lost In Translation, Drama
Ron Howard, A Beautiful Mind, Drama
Joe Biden, Your Big Hat, Sports
Barack Obama, The Stubborn Goat, Drama
Steve Smith, 2 Beautiful Ants, Suspense
Jared Hess, Napoleon Dynamite, Comedy
Jack Daniels, Field of Dreams, Drama

我需要按姓氏字母顺序排序的第一个字段。这行得通。

然后我需要在 HTML 表格中显示数组,并且能够将列数设置为 5。我需要每个单元格保存 CSV 文件中的一行,然后从左向右移动以填充表格。

我尝试过的一切都让我快到了,但表格无法正确显示 - 它缺少 td 标记或最后一个 td 中没有  

任何帮助将不胜感激。

这是我目前所拥有的:

 $file = fopen("dummy-list.csv", "r") or die('cannot open file');

// sort
$surnames = array();
$rows = array();
//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($file, 0, ',') )) {
    //extract surname from the first column
    //this should match the last word before the comma, if there is a comma
    preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
    $surnames[] = $m[1];
    $rows[] = $row;
}
//fclose($file);
//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);
//print_r($rows);


// set # of table columns
$numCols = 4;
$i=0;


echo '<table border="1" align="center"><tr>' . "\n";
foreach( $rows as $rows2 )
{

if ($i % $numCols == 0 && $i != 0) 
    echo "</tr>\n<tr>"; // every time but the first

    echo '<td>';

    foreach( $rows2 as $key )
    {
            echo $key . '<br />';
        $i++;
    }
    echo "</td>\n";
}


while ($i++ % $numCols != 0) 
echo '<td>&nbsp;</td>' . "\n"; // fill in empty cells


// end table
echo '</tr></table>' . "\n\n\n";

【问题讨论】:

  • 我通过将 CSV 转换为 JSON 并为此使用 DataTables 来实现这一点
  • 这是我们在 1998 年使用的表格。
  • 你有例子吗?
  • GolezTrol - 你的评论没有帮助,除非你要推荐你现在在 2016 年使用的东西......

标签: php html csv html-table


【解决方案1】:

保留您的代码:

改变这个:

while ($i++ % $numCols != 0) 
echo '<td>&nbsp;</td>' . "\n"; // fill in empty cells

为了它:

$mod = $numCols-count($rows)%$numCols;

for($i=0;($i < ($mod) && $mod != $numCols);$i++)
    echo '<td>&nbsp;</td>' . "\n";

并解决您的问题!

【讨论】:

    【解决方案2】:

    你只需要稍微修改你的逻辑。目前,您的脚本不会跟踪您所在的列,因此它无法知道要填充多少个单元格。

    最大的逻辑问题是:

    while ($i++ % $numCols != 0) 
    echo '<td>&nbsp;</td>' . "\n"; // fill in empty cells
    

    所做的只是检查列数是否可以由 $i 设计。所以,在 $i 达到 3 之后,它停止了。 (在这种情况下 4/3 != 0)

    以下作品:

    $file = fopen("dummy-list.csv", "r") or die('cannot open file');
    
    // sort
    $surnames = array();
    $rows = array();
    //build array of surnames, and array of rows
    while (false != ( $row = fgetcsv($file, 0, ',') )) {
       //extract surname from the first column
       //this should match the last word before the comma, if there is a comma
       preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
       $surnames[] = $m[1];
       $rows[] = $row;
    }
    //fclose($file);
    //sort array of rows by surname using our array of surnames
    array_multisort($surnames, $rows);
    //print_r($rows);
    
    
    // set # of table columns
    $numCols = 4;
    $i=0;
    $cellpos = 0; //count columns
    
    echo '<table border="1" align="center"><tr>' . "\n";
    //use the amount of rows as a divisor
    for($c=0; $c<Count($rows); $c++ )
    {
    
        if ($i % $numCols == 0 && $i != 0){
           echo "</tr>\n<tr>"; // every time but the first
           $cellpos=0;  //reset our column position
        }
    
        echo '<td>';
        //then, call each csv row explicitly
        foreach( $rows[$c] as $key )
        {
            echo $key . '<br />';
            $i++;
        }
        echo "</td>\n";
        $cellpos++;  //track our column position
    }
    
    while ($cellpos++ < $numCols)
    echo '<td>&nbsp;</td>' . "\n"; // fill in empty cells
    
    
    // end table
    echo '</tr></table>' . "\n\n\n";
    

    我添加了 $cellpos 变量来计算每行中的 td,作为您的填充。每次开始新行时都会重置。如果您通过脚本跟踪该变量,您将看到我的更改。

    此外,如果您想对这些键执行更具体的操作,您可以直接调用它们,而不仅仅是循环遍历行。只需更改&lt;td&gt; 标签之间的代码即可。

    echo '<td>';
    
    //then, call each csv celldata explicitly
    
        echo '<a href="' . $rows[$c][0]. '"><img src="'. $rows[$c][1] . '" /><br />' .$rows[$c][2] . '</a>';
        $i++;
    
    echo "</td>\n";
    

    【讨论】:

    • dval - 如果我将 csv 更改为:Mike Judge,artists/judge.php,images/bikini.jpg Larry Wachowski,artists/wachowski.php,images/wachowski.jpg Sofia Coppola,artists/ coppola.php,图像/coppola.jpg
    • 这段代码不起作用://echo $key。 '
      ';回声 "
      ";回声 $rows[$c][0] 。 "
      ";
    • @user888864 您需要正确格式化该行,使用双引号定义字符串,但字符串也有双引号。您需要在 HTML 周围使用单引号,或者转义字符串中的所有双引号。这是格式正确的字符串:echo '&lt;a href="' . $rows[$c][0]. '"&gt;&lt;img src="'. $rows[$c][1] . '" /&gt;&lt;br /&gt;' .$rows[$c][2] . '&lt;/a&gt;'; 此外,您需要注释掉 foreach 循环,因为您现在不是循环遍历行,而是显式声明键 $rows[$c][0] 等...我会更新我的答案反映这一点
    • “显式声明密钥”是指“显式调用”。
    • 当我注释掉 foreach 循环时,我得到了额外的 td 单元格......很抱歉很痛苦......但非常感谢你的帮助。是否有一个网站可以演示此代码,以便我更容易看到完整的代码? ideone.com 还是 codepen.com?
    【解决方案3】:

    您可以使用MOD运算符检查您是否在列的末尾,然后结束该行,然后开始一个新的:

    $cols = 4;
    $count = count($rows);
    
    $table_html ="<tr>";
    for($i=0; $i < $count; ++$i){
        $table_html.= '<td>' . implode("<br>", $rows[$i]) . '</td>';
        if($i != 0 && ($i % $cols == 0)){
            $table_html.="</tr>";
        }
    }
    $table_html.="</tr>";
    echo $table_html;
    

    【讨论】:

      猜你喜欢
      • 2013-09-20
      • 2017-12-28
      • 2016-04-10
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      相关资源
      最近更新 更多