Posts tagged ‘array’

Usage

Pass an array of arrays, and will return an HTML table. This is useful for returning database records in a “pretty” format. I could never find anything that would work quite the way i wanted it to, so i wrote my own.

$arr = array();
$arr[] = array('Name','SomeValue');
$arr[] = array('Greg','12345');
echo renderArrayToTable($arr,'true');

Code

function renderArrayToTable($array_of_arrays,$first_row_headers=false) {
	$rstr = '';
	$i=0;
	$rstr .= '<table border="1" cellspacing="0" cellpadding="5">';
	foreach ($array_of_arrays as $arr) {
		if (is_array($arr)) {
			$pre = (($first_row_headers)&&($i==0))?'<th>':'<td>';
			$post = (($first_row_headers)&&($i==0))?'</th>':'</td>';
			$rstr .= '<tr>';
			foreach ($arr as $key => $value) {
				$rstr .= $pre.$value.$post;
			}
			$rstr .= '</tr>';
		}
		$i++;
	}
	$rstr .= '</table>';
	return $rstr;
}