[eluser]xwero[/eluser]
Yesterday my attention was drawn to the html table class and because it got stuck in my head i created the html table plugin.
It does everything the html table class does except for adding a database object as table content.
The benefits are :
- no markup in the controller
- more in control of the output
- multiple header rows
Code:
<?php
function table($view_path,$body,$header= array(),$footer = array(),$columns=0)
{
if( ! is_array($body))
{
return '';
}
// return $header and $footer parameters to default state in case a
// developer used a string when calling the function
if( ! is_array($header)){ $header = array(); }
if( ! is_array($footer)){ $footer = array(); }
// if the header and footer parameters are a single array a two dimensional
// array is created
if( count($header) > 0 && ! is_array($header[0])) { $header = array($header); }
if( count($footer) > 0 && ! is_array($footer[0])) { $footer = array($footer); }
// create columns from single array
if(is_numeric($columns) && $columns > 0)
{
$body = array_chunk($body,$columns);
}
if(! is_array($body[0])) { $body = array($body); }
ob_start();
include($view_path);
return ob_get_clean();
}
Put this code in a file named table_pi.php. To get the view path easy you can add the following function to the plugin file or another helper that you know is loaded.
Code:
function view_path($view)
{
$CI =& get_instance(); // You can add file_exists check after this line
return $CI->load->_ci_view_path.$view.EXT;
}
And it's good to go. Some usage examples
Code:
/* break array up into multiple columns */
$body = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve');
echo table(view_path('table/columns'),$body,'','',3);
// table/columns.php
<table><?php foreach($body as $row): ?>
<tr><?php foreach($row as $cell): ?>
<td><?php echo $cell ?></td><?php endforeach ?>
</tr><?php endforeach ?>
</table>
/* header, footer, body */
$header = array(array(1,2,3),array('multiple','rows','possible'));
$body = array(array(4,5,6),array(7,8,9));
$footer = array('no','wrapper array','needed');
echo table(view_path('table/hbf'),$body,$header,$footer);
// table/hbf.php
<table>
<thead><?php foreach($header as $row): ?>
<tr><?php foreach($row as $cell): ?>
<th><?php echo $cell ?></th><?php endforeach ?>
</tr><?php endforeach ?>
</thead>
<tbody><?php foreach($body as $row): ?>
<tr><?php foreach($row as $cell): ?>
<td><?php echo $cell ?></td><?php endforeach ?>
</tr><?php endforeach ?>
</tbody>
<tfoot><?php foreach($footer as $row): ?>
<tr><?php foreach($row as $cell): ?>
<td><?php echo $cell ?></td><?php endforeach ?>
</tr><?php endforeach ?>
</tfoot>
</table>
Enjoy!
UPDATE 1 : If $header, $body or $footer are a single array it will be transformed to a two dimensional array
UPDATE 2 : based on sophistry's response i removed the nested loop and replaced the not empty check with a count higher than 0 check.