我将如何循环通过一个文件来构建一个表PHP



我需要循环浏览一个文件并生成一个包含信息(姓名、电话号码、电子邮件)的表,但我似乎可以得到它

<?php
$sortedArr = array();
$file = file("files/info.txt");
foreach($file as $v){
    $tempArr = explode(",",$v);
    $tempArr[1] = substr($tempArr[1],0,-1);
    $str = "$tempArr[1], $tempArr[0]";
    array_push($sortedArr,$str);
}
$arrLen = count ($sortedArr);
    $rowLen = count ($sortedArr[0]);
    $tbl = "<table border= '1'>";

 $tbl .= "<tr>";
 for ($i=0;$i<$arrLen;$i++)
 {
 $tbl .= "</tr>";
  for ($l=0;$l<$rowLen;$l++)
   {
   $tbl .= "<td>" . $arr[$i][$l] . "</td>";
   } 
}
 $tbl .= "</tr>";
$tbl .= "</table>";
?>

我以为我可以把所有的东西都放进$sortedArr,然后循环通过它,但我运气不太好。谢谢你提前提供的帮助。

以下是文件/info的示例。

tom,jones,5236895214,kjsdlfkjslfkj@ldjlf
jared,smith,2351547809,blahlbahlbah
john,doe,8745125489,dsjfksjfkjhsdkj
tom,atkins,5214523658,jhdfjashdfkjhsdkfj

好的,首先。在PHP中,使用增量for ()循环并跟踪$i几乎从来都不是正确的做法。简单的迭代最好使用foreach ()循环。通过切换到foreach,您将消除对所有count()记帐$i, $l的需要。

以下是的全部操作

//Starting from the beginning:
$sortedArr = array();
$file = file("files/info.txt");
foreach($file as $v){
    $tempArr = explode(",",$v);
    // Get the first and second values
    // Not sure what the substr() was for
    // since it would remove the last letter of the lastname...
    // Let's omit that.
    $str = $tempArr[0] . ' ' . $tempArr[1];
    // Looks like you want to join the names 0,1
    // and use the rest as they are...
    // The joined string back into the first index
    $tempArr[0] = $str;
    // and get rid of the second since it's joined with the first
    unset($tempArr[1]);
    // Append the array onto your big:
    array_push($sortedArr, $tempArr);
}
// Now open your table, then use 2 foreach
// loops to build the rows and columns, opening and
// closing the <tr> inside each iteration of the outer loop.
$tbl = "<table border='1'>";
// Outer loop is rows
foreach ($sortedArr as $row) {
   // Start a row, close it later
   $tbl .= '<tr>';
   // Inner loop is columns
   foreach ($row as $col) {
      $tbl .= '<td>' . htmlspecialchars($col) . '</td>';
   }
   $tbl .= '</tr>';
}
// Close your table
$tbl .= '</table>';

相关内容

  • 没有找到相关文章

最新更新