#native_company# #native_desc#
#native_cta#

text-table

By Tim ODonnell
on August 10, 2002

Version: 1

Type: Function

Category: Other

License: GNU General Public License

Description: These functions allow you to create simple text tables for use in textonly emails, etc. To use them simly call:

$table = text_table ($data, “-“, “|”);

$data should be a two dimensional array containing your rows and columns. Rows should be first, columns second. $data[0][3] would be row 0, column 3. The ‘-‘ and ‘|’ are the horizontal and seperating characters, respectively.

Let me know if you find this useful.

<?php
// ********************************************************************
// Text table generation functions.
// By Tim O'Donnell, [email protected]
// Call text_table () to generate a textual table.
// Sizing, etc. is handled automatically.
// $data is a two dimensional array corresponding to your rows and columns.
// $h and $v are your horizontal and vertical character seperators, respectively.
//                   Let me know if you find this useful.
// ********************************************************************

function text_table ($data, $h = "-", $v = "|") {
	
	// Compute the largest value for each column:
	
	$count = count ($data);
	
	$largest[0] = "";
	
	for ($i=0; $i < $count; $i++) {
		
		$row = $data[$i];
		
		foreach ($row as $index => $col) {
			
			$len = strlen($col);
			if (!array_key_exists($index, $largest) OR $largest[$index] < $len) $largest[$index] = $len;
			
		}
		
	}
	
	// We now have $largest, a 1 dimensional array containing the largest lengths of each column.
	
	// Now we feed this into the row generator:
	
	$out = text_table_line ($largest, $h);
	
	for ($i=0; $i < $count; $i++) {
	
		$row = $data[$i];
		$out .= text_table_row ($row, $largest, $h, $v);
		
	}
	
	return $out;
	
	
}

function text_table_row ($row, $largest, $h, $v) {
	
	$out = "";
	
	foreach ($row as $index => $col) {
		
		$colpad = str_pad ($col, $largest[$index]);
		$out .= "$v $colpad ";
		
	}
	
	$out .= "$vn" . text_table_line ($largest, $h);
	
	
	return $out;
	
}

function text_table_line ($largest, $h) {
	
	$totlength = array_sum($largest) + (count($largest) * 3) + 1; // We add count($largest) because of the space on the $out .= line.	
	$out = str_repeat ($h, $totlength) . "n";
	
	return $out;
}

?>