Jump to content

From array into table


tommy20

Recommended Posts

I have a text file with a sinlge line of text on each line. How do you read this so that it can be displayed in a table two columns wide.

 

I have tried reading it into an array and then looping through the array but I can only get it display in a single column.

 

Is this the correct approach

 

 

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

simple code to display 2 columns from file .. just update $lines to point to your file.

 

<?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.

 

now, a zig-zag pattern is one way, but you can also achieve a one-two column pattern as well with some tweaking.

 

zig-zag:

 

first entry second entry

third entry fourth entry

 

one-two column:

 

first entry fourth entry

second entry fifth entry

third entry sixth entry

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.