PHP爆炸多维数组

时间:2012-08-06 07:23:02

标签: php arrays multidimensional-array explode dimensional

我正在使用file_get_contents()导入文本文件。 在文本文件中,格式如下(示例):

3434,83​​,8732722
834,93,4983293
9438,43933,34983

等等...基本上它遵循模式:整数,逗号分割它,第二个整数,另一个逗号分割它,第三个整数,然后一个新行开始。我需要将其放入一个格式如下的表中。换句话说,我会有一个3列表,文本文件中的每一行都是表格中的新行。

必须使用< table>将其转码为一个简单的html表格。 < TR>和< td>

我从未使用过多维数组并用它来分割文本。这就是我寻求帮助的原因。对此,我真的非常感激! :)

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

$filename = 'abc.txt';
$content = file_get_contents($filename);
$explodedByBr = explode('<br/>', $content);
$table = "<table border='1'>";
foreach ($explodedByBr as $brExplode) {
  $explodedByComma = explode(',', $brExplode);

  $table .= "<tr>";
  foreach ($explodedByComma as $commaExploded) {
    $table .= "<td>" .$commaExploded. "</td>";
  }
  $table .= "<tr/>";
}
$table .= "</table>";

echo $table;

abc.txt包含以下格式的数据:

3434,83​​,8732722
834,93,4983293
9438,43933,34983

答案 1 :(得分:0)

<?php
    $file = 'path/to/file.txt';
    echo '<table>';
    while(!feof($file)) {
        $line = fgets($file);

        echo '<tr><td>' . implode('</td><td>',explode(',',$line)) . '</td></tr>';
    }
    echo '</table>';
?>

答案 2 :(得分:0)

试试这个:

将文件读入数组,然后通过传递array_walk处理数组的每一行来对其进行列化。

<?php
function addElements( &$v, $k ) {
    $v1 = explode( ',', $v ); // break it into array
    $v2 = '';
    foreach( $v1 as $element ) {
        $v2 .= '<td>'.$element.'</td>';
            // convert each comma separated value into a column
    }
    $v = '<tr>'.$v2.'</tr>'; // add these columns to a row and return
}

// read the whole file into an array using php's file method.
$file = file( '1.txt' );
// now parse each line of the array so that we convert each line into 3 columns.
// For this, i use array_walk function which calls a function, addElements, 
// in this case to process each element in the array.
array_walk( $file, 'addElements' );
?>
<html>
     <head></head>
     <body>
         <table border="0">
             <?php echo implode('',$file);?>
         </table>
     </body>
</html>

希望它有所帮助。请参阅filearray_walk的php文档。这些都是简单方便的功能。