PHP Array to Table

2.12.2008

Ich habe mir eine kleine PHP-Funktion geschrieben, welche ein eindimensionales Array in eine mehrspaltige Tabelle verwandelt.

/**
 * Generates a multi-column table from an array 
 *
 * @version 0.9  
 * @param array		Array to process 
 * @param columns	Number of columns to return  
 * @optional id		ID attribute to attach to the table
 * @optional class	CSS class attribute to attach to the table 
 */
function generate_table($array, $columns, $table_id='', $table_class='') {
	$array_size = count($array);
	$col_size = ceil($array_size / $columns);
 
	$table = "<table";
	$table .= !empty($table_id) ? " id='".$table_id."'" : '';
	$table .= !empty($table_class) ? " class='".$table_class."'" : '';
	$table .= ">\n";
	for ($i = 0; $i < $col_size; $i++) {
		$table .= "\t<tr>";
		for ($j = 0; $j < $columns; $j++) {
			$table .= (($i+$j*$col_size) < $array_size) ? '<td>'.$array[$i+$j*$col_size].'</td>' : '<td>&nbsp;</td>';
		}
		$table .= "</tr>\n";
	}
	$table .= "</table>\n";
 
	return $table;
}

Verbesserungsvorschläge und Flame-Attacken sind willkommen ;)

Fork me on GitHub

Kommentare

Generate table from array…

Just for exercise, I’ve rewritten the two loops. The function become.
I don’t know if it is more efficient, you should try (I can’t do it now)….

Generate table from array…

eineki, your code looks great, and it works perfectly except that the ordering of the array output is horizontal, while the one in my solution returns vertically ordered columns. (i hope you understand, it’s difficult to explain in english :) ) but tha…

Generate table from array…

You shouldnt use count() in while, very inefficient. You should use a for loop and cache the length…

Generate table from array…

Not really an improvement on this code, but I’m writing a database class (extending PDO) that returns a statement object (extending PDOStatement). In the statement class I wrote a fetchTable() method that returns a html table based on the resultset. S…

Generate table from array…

einiki, Thank you very much for your code. I was dreading making a TON of tables cells and this script made my life so much easier. I nearly cried at how quickly all my perfect tables were generated. All I had was two td’s per row so I just passed in …

Hinterlasse einen Kommentar

Dein Kommentar:

XHTML: Sie dürfen folgende Tags verwenden: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Kategorien

Switch to our mobile site