Using column filtering with Console_Color

In this example we use Console_Table::addFilter() to colorize our table cells according to their value. Colorization is very easy using PEAR's Console_Color package. Just make sure you set the "color" parameter of Console_Color's constructor - otherwise you will see weird column widths.

After filling our table object with headers and data, we add an output filter by specifying a callback function. The first parameter to addFilter is the column number that shall be formatted, beginning with 0. Due to backwards compatibility with PHP4, addFilter requires a variable as second parameter, even if you just want to specfiy a simple function name.

We also have Console_Table align the "Profit" column right so that the commas are aligned equally.

<?php
require_once 'Console/Table.php';
require_once 
'Console/Color.php';

//those could come e.g. from database
$data = array(
    array(
2001128.23),
    array(
2002256.42),
    array(
200310.21),
    array(
2004, -25.79),
    array(
20050),
    array(
2006982.12),
);

//prepare table
$tbl = new Console_Table(
    
CONSOLE_TABLE_ALIGN_LEFTCONSOLE_TABLE_BORDER_ASCII,
    
1null,
    
true//this is important when using Console_Color
);
$tbl->setHeaders(
    array(
'Year''Profit')
);
$tbl->addData($data);

//add filter callback to colorize our profit column values
$callback 'colorize';
$tbl->addFilter(1$callback);

//Values should be aligned right
$tbl->setAlign(1CONSOLE_TABLE_ALIGN_RIGHT);


echo 
$tbl->getTable();


/**
* Wraps Console color codes around $value,
* depending if its larger or smaller 0.
*
* @param float $value Value (column 1)
*
* @return string Colorful value
*/
function colorize($value)
{
    
$str number_format($value2',''');
    if (
$value 0) {
        return 
Console_Color::convert('%r' $str '%n');
    } else if (
$value == 0) {
        return 
$str;
    } else {
        return 
Console_Color::convert('%g' $str '%n');
    }
}
?>

The code above creates the following output, except that "Profit" values larger than 0 are colored in green, while the ones smaller zero are in red.


+------+--------+
| Year | Profit |
+------+--------+
| 2001 | 128,23 |
| 2002 | 256,42 |
| 2003 |  10,21 |
| 2004 | -25,79 |
| 2005 |   0,00 |
| 2006 | 982,12 |
+------+--------+