Jump to content

A Table with Randomized Cell Content


iwato

Recommended Posts

BACKGROUND: The following function creates a table with randomized cell content. The function accepts a specified number of observation $obs. The $cols parameter allows the user to choose the number of columns. The function then selects the appropriate number of rows to accommodate the number of elements in the $input array. The table is offered without style formatting and has been thoroughly tested for all possible values of $cols. In short, it works.QUESTION: Is the section of code that actually builds the table efficient? It works, but it feels awkward, and I would like to streamline it, if possible. Any suggestions?

	function create_randable($obs, $cols, $name, $caption='', $style='') {					if (($obs >= $cols) && ($cols > 0)) {			if ($obs % $cols != 0) {				$rows = ceil($obs/$cols);				$empty = ($rows * $cols) - $obs;			} else {				$rows = $obs/$cols;				$empty = 0;			}		} else {			echo 'The number of columns must be less than the number of observations and some number greater than zero.';		}		$input = range(1,$obs);		shuffle($input);		echo '<table id=\'', $name, '\'>';		$k=0;		echo '<tr><td></td>';		for ($i=0; $i<$cols; $i++) {			echo '<th class=\'Header\'>col ', $i+1, '</th>'; 		}		echo '</tr>';		for ($i=0; $i<$rows; $i++) {			echo '<tr><th class=\'Header\'>row ', $i+1, '</th>';			for ($j=0; $j<$cols; $j++) {										echo '<td>', @$input[$k], '</td>';				$k++;			}			echo '</tr>';		}		echo '<tr class=\'Footnote\'><td colspan=\'', $cols+1, '\'><hr />number of observations: ', $obs, '<br />			number of columns: ', $cols, '<br />			number of rows: ', $rows, '<br />			number of empty cells: ', $empty, '</td></tr';		echo '<caption>', $caption, '</caption>';		echo '</table>';	}

Roddy

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...