lithium\console\Command::columns()

public method

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 = array(
    array('Name', 'Age'),
    array('----', '---'),
);
foreach($users as $user) {
    $output[] = array($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, array('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

Returns

void

Source

	public function columns($rows, $options = array()) {
		$defaults = array('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);
	}