'count',
);
- switch ( $assoc_args['format'] ) {
- case 'table':
- $table = new \cli\Table();
-
- $table->setHeaders( $fields );
-
- foreach ( $terms as $term ) {
- $line = array();
-
- foreach ( $fields as $field ) {
- $line[] = $term->$field;
- }
-
- $table->addRow( $line );
- }
-
- $table->display();
-
- WP_CLI::line( 'Total: ' . count( $terms ) . ' terms.' );
- break;
- case 'csv':
- case 'json':
- $output_terms = array();
-
- foreach( $terms as $term ) {
- $output_term = new stdClass;
- foreach( $fields as $field ) {
- $output_term->$field = $term->$field;
- }
- $output_terms[] = $output_term;
- }
-
- if ( 'json' == $assoc_args['format'] )
- echo json_encode( $output_terms );
- else
- WP_CLI\Utils\output_csv( $output_terms, $fields );
- break;
- }
-
+ WP_CLI\Utils\format_items( $assoc_args['format'], $fields, $terms );
}
/**
}
/**
+ * Output items in a table, JSON, or CSV
+ *
+ * @param string $format Format to use: 'table', 'json', 'csv'
+ * @param array $fields Named fields for each item of data
+ * @param array $items Data to output
+ */
+function format_items( $format, $fields, $items ) {
+
+ switch ( $format ) {
+ case 'table':
+ $table = new \cli\Table();
+
+ $table->setHeaders( $fields );
+
+ foreach ( $items as $item ) {
+ $line = array();
+
+ foreach ( $fields as $field ) {
+ $line[] = $item->$field;
+ }
+
+ $table->addRow( $line );
+ }
+
+ $table->display();
+ break;
+ case 'csv':
+ case 'json':
+ $output_items = array();
+
+ foreach( $items as $item ) {
+ $output_item = new \stdClass;
+ foreach( $fields as $field ) {
+ $output_item->$field = $item->$field;
+ }
+ $output_items[] = $output_item;
+ }
+
+ if ( 'json' == $format )
+ echo json_encode( $output_items );
+ else
+ output_csv( $output_items, $fields );
+ break;
+ }
+}
+
+/**
* Output data as CSV
*
* @param array $rows Array of rows to output