我如何循环文件来构建PHP表

时间:2014-04-18 02:34:17

标签: php file loops

我需要遍历文件并生成一个包含信息(姓名,电话号码,电子邮件)的表格,但我似乎可以得到它。到目前为止这是我的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然后循环执行,但我没有太多运气。感谢您的帮助。

以下是文件/信息的示例。

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

1 个答案:

答案 0 :(得分:1)

好的,首先是第一件事。在PHP中,使用增量for ()循环并跟踪$i几乎不是正确的行动方案。最简单的迭代最好用foreach ()循环完成。通过切换为foreach,您将无需进行所有count()会计核算,$i, $l

Here's the whole thing in action

//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>';