Transformar un Array a tabla HTML
Hoy mirando la pagina de @Aidan me he topado con una función bastante interesante. Si el otro día publicaba una función que transforma una tabla HTML a array, @Aidan ha creado lo contrario. Una función que transforma un array a tabla, pero dando unos toques de personalización bastante buenos.
Si queremos crear una tabla simple a partir de un array simple solo tenemos que poner nuestro array en la primera variable y imprimirá en la web directamente el código de la tabla, pero si quisiéramos introducir un array multimimensional, metiendo tablas en las celdas, solo tendríamos que poner a true la 2º variable de la función.
Si a demás en vez de que se imprima directamente los datos queremos obtener el string de salida podemos hacerlo directamente con solo cambiar la 3º variable a true, y si queremos cambiar las variables en blanco de nuestro array a algún texto (interesante para hacer tablas de contabilidad y poder poner 0 en los espacios en blanco por ejemplo) solo tenemos que poner el texto a sustituir en el 4º lugar.
-
function array2table($array, $recursive = false, $return = false, $null = ' '){
-
// Sanity check
-
-
// Start the table
-
$table = "<table>\n";
-
// The header
-
$table .= "\t<tr>";
-
// Take the keys from the first row as the headings
-
$table .= '<th>' . $heading . '</th>';
-
}
-
$table .= "</tr>\n";
-
-
// The body
-
foreach ($array as $row) {
-
$table .= "\t<tr>" ;
-
foreach ($row as $cell) {
-
$table .= '<td>';
-
-
// Cast objects
-
// Recursive mode
-
$table .= "\n" . array2table($cell, true, true) . "\n";
-
} else {
-
$null;
-
}
-
$table .= '</td>';
-
}
-
$table .= "</tr>\n";
-
}
-
// End the table
-
$table .= '</table>';
-
// Method of output
-
if ($return === false) {
-
echo $table;
-
} else {
-
return $table;
-
}
-
}
Ejemplo de uso:
Podría parecerte interesante:
Código:
http://dev.ellislab.com/svn/CodeIgniter/trunk/system/libraries/Table.php
Ejemplos:
http://codeigniter.com/user_guide/libraries/table.html
Muy bueno Imzyos, sobre todo el segundo link! muchas gracias