How to convert PHP array to ascii (console) table

I’ve got an interesting task on my work – make a table with pretty-print in console. I’ve googled it by request like php associative array to text table, but didn’t find anything which is good for me. So I’ve developed a package on the github and put it to the composer so you’re now able to use if in your projects 🙂

Assuming, I’ve written a PHP-class, which allows to transform associative arrays to cool ASCII tables. I’d want to support this package in the future with adding some cool features like color print in console, printing formats, charset, etc.

The package is pretty simple in use:

<?php

use dekor\ArrayToTextTable;

$data = [
    [
        'id' => 1,
        'name' => 'Denis Koronets',
        'role' => 'php developer',
    ],
    [
        'id' => 2,
        'name' => 'Maxim Ambroskin',
        'role' => 'java developer',
    ],
    [
        'id' => 3,
        'name' => 'Andrew Sikorsky',
        'role' => 'php developer',
    ]
];

echo (new ArrayToTextTable($data))->render();

Will print the next output:

+----+-----------------+----------------+
| id | name            | role           |
+----+-----------------+----------------+
| 1  | Denis Koronets  | php developer  |
| 2  | Maxim Ambroskin | java developer |
| 3  | Andrew Sikorsky | php developer  |
+----+-----------------+----------------+

Github: https://github.com/deniskoronets/php-array-table

Packagist: https://packagist.org/packages/dekor/php-array-table

Click to rate this post!
[Total: 2 Average: 5]

You May Also Like

About the Author: deniskoronets

2 Comments

  1. Хэй, взялась за подобный таск на работе. А подскажи, а как дополнить , дабы оно работало для данного массива

    private $data = array(
    array(
    ‘House’ => ‘Baratheon’,
    ‘Sigil’ => ‘A crowned stag’,
    ‘Motto’ => ‘Ours is the Fury’,
    ),
    array(
    ‘Leader’ => ‘Eddard Stark’,
    ‘House’ => ‘Stark’,
    ‘Motto’ => ‘Winter is Coming’,
    ‘Sigil’ => ‘A grey direwolf’
    ),
    array(
    ‘House’ => ‘Lannister’,
    ‘Leader’ => ‘Tywin Lannister’,
    ‘Sigil’ => ‘A golden lion’
    ),
    array(
    ‘Q’ => ‘Z’
    )
    );

    Тобишь для массива где есть уникальные ключи.

    Слава Україні!

    1. насколько я помню, нужно доп цикл чтобы превратить массив в одинаковый за видом для отрисовки. очень давно не трогал эту библиотеку.

Leave a Reply

Your email address will not be published.