NYCPHP Meetup

NYPHP.org

[nycphp-talk] PEAR HTML_Table

Jose Villegas jv_nyphp at duikerbok.com
Fri Sep 10 20:10:50 EDT 2004


On Sep 10, 2004, at 7:28 PM, John Corry wrote:
>
> All the examples I can find show building the table from a 
> multidimensional
> array...is there a way to just specify number of cols, an array of 
> data and
> get back a table?
>


Sorry John, I missed the part about not wanting a multidimensional 
array. I made some slight modifications that should make this class 
work with a simple array. I didn't test it, so let me know if it 
doesn't work.

Now your templates should look like this:

$cellTemplate = '<td><img src="images/{IMAGE}.jpg"></td>
';
$emptyTemplate = '<td></td>
');

Your array of values can look like this:
$values = array(
	'sunset',
	'palm-trees'
);

The rows are created the same way:
$trg = new TableRowGenerator($cellTemplate, $emptyTemplate, 3);
$tableRows = $trg->parse($values);

-jose
www.josevillegasdesign.com

******

class TableRowGenerator
{
	var $cellTemplate = null;
	var $emptyCellTemplate = null;
	var $maxColumns = 1;
	var $rowPrefix = '<tr>
';
	var $rowSuffix = '</tr>
';
	var $cellDivider = '';
	
	// Private properties.
	var $nextColumn = 1;
	
	function TableRowGenerator($cellTemplate, $emptyCellTemplate, 
$maxColumns)
	{
		$this->cellTemplate = $cellTemplate;
		$this->emptyCellTemplate = $emptyCellTemplate;
		$this->maxColumns = $maxColumns;
	}
	
	function parse($values)
	{
		if (!$values) return;
		$valuesCount = count($values);
		if ($valuesCount == 0) return;

		// Set up tag elements.
		$prefix = '{';
		$suffix = '}';

		$mod = $valuesCount % $this->maxColumns;
		if ($mod != 0)
		{
			$emptyCellCount = $this->maxColumns - $mod;
			for ($i = 0; $i < $emptyCellCount; $i++) $values[] = null;
		}

		$result = '';
		foreach($values as $valueSet)
		{
			// Add row prefix if this is the first cell in the row.
			if ($this->nextColumn == 1) $result .= $this->rowPrefix;
			
			// Assign appropriate cell template.
			if ($valueSet)
			{
				$setResult = $this->cellTemplate;
				//foreach($valueSet as $key => $value)
					$setResult = str_replace('{IMAGE}', $value, $setResult);
			}
			else $setResult = $this->emptyCellTemplate;
			$result .= $setResult;

			if ($this->nextColumn == $this->maxColumns)
			{
				$result .= $this->rowSuffix;
				$this->nextColumn = 1;
			}
			else
			{
				$result .= $this->cellDivider;
				$this->nextColumn++;
			}
		}
		return $result;
	}
}




More information about the talk mailing list