Jump to content

Array to table


tommy20

Recommended Posts

Hi,

 

I have a text file that has lines of text. I want to read in the files and display them on a webpage. The thing is that I need to split the string into two and display it in a table with two columns.

 

I've tried the following code to get a table but I can get to split the string in tow and get it to display in two different cells of the table. Any idea

 

 

<?php

$lines = file ('/path/to/your/file');

$counted = count ($lines);

 

#set counters/stepping vars;

$g = 0;

$rowcount = 0;

 

#columns - how many columns to display;

$columns = 2;

 

echo '<table width="100%">';

for ($i=0; $i<=$counted;)

{

  $rowcount++;

  $g = ($i + $columns);

 

  echo '<tr>';

 

  for( ; $i<$g; $i++)

  {

  echo '<td valign="top">';

    echo $lines[$i];

  echo '</td>';

  }

  echo '</tr>';

}

echo '</table>';

?>

EDIT: so you understand what's going on:

 

code uses file() to get contents of file in array.  from there, using nested for() loops, contents from array are displayed in a zig-zag pattern until count($lines) (aka, total number of lines in file/values in array) are reached.

 

Link to comment
https://forums.phpfreaks.com/topic/180186-array-to-table/
Share on other sites

It's not clear from your post if you want to have two lines of the text file appear in one column (each in a separate cell) or if you want to split each line into two cells of the table. If you need each line split we need to know what the rule is for splitting them.

 

If it is the former you want, try this (not tested):

<?php 
$maxColumns = 2;
$currentCol = 1;

$lines = file ('/path/to/your/file'); 

foreach ($lines as $line)
{
    if ($currentCol==1)
    {
        $tableHTML .= "  <tr>\n";
    }

    $tableHTML .= "    <td valign=\"top\">{$line}</td>\n";
    $currentCol++;

    if ($currentCol>$maxColumns)
    {
        $tableHTML .= "  </tr>\n";
        $currentCol==1
    }
}

if($currentCol<=$maxColumns)
{
    for ($currentCol; $col<=$maxColumns; $currentCol++)
    {
        $tableHTML .= "    <td valign=\"top\"> </td>\n";
    }
    $tableHTML .= "  </tr>\n";
}

?>


<table width="100%">
<?php echo $tableHTML; ?>
</table>

Link to comment
https://forums.phpfreaks.com/topic/180186-array-to-table/#findComment-950511
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.