lithium\console\Command::columns()
Writes rows of columns.
This method expects asceding integer values as the keys, which map to the appropriate columns. Currently, there is no special "header" option, but you can define them for your own.
Example Usage:
$output = [
['Name', 'Age'],
['----', '---'],
];
foreach($users as $user) {
$output[] = [$user->name, $user->age];
}
$this->columns($output);
Would render something similar to:
Name Age
---- ---
Jane Doe 22
Foo Bar 18
This method also calculates the needed space between the columns. All option params given
also get passed down to the out()
method, which allow custom formatting. Passing something
like $this->columns($output, ['style' => 'red]
would print the table in red.
Parameters
-
array
$rows
The rows to print, with each column as an array element.
-
array
$options
Optional params:
- separator : Different column separator, defaults to
\t
- style : the style name to wrap around the columns output
- separator : Different column separator, defaults to
Returns
voidSource
public function columns($rows, $options = []) {
$defaults = ['separator' => "\t", "error" => false];
$options += $defaults;
$lengths = array_reduce($rows, function($columns, $row) {
foreach ((array) $row as $key => $val) {
if (!isset($columns[$key]) || strlen($val) > $columns[$key]) {
$columns[$key] = strlen($val);
}
}
return $columns;
});
$rows = array_reduce($rows, function($rows, $row) use ($lengths, $options) {
$text = '';
foreach ((array) $row as $key => $val) {
$text = $text . str_pad($val, $lengths[$key]) . $options['separator'];
}
$rows[] = $text;
return $rows;
});
if ($options['error']) {
$this->error($rows, $options);
return;
}
$this->out($rows, $options);
}