LoginSignup
1
0

More than 1 year has passed since last update.

PHPで連想配列をPostgreSQLのpsql風にテーブル表示する

Posted at

連想配列をPostgreSQLのpsql風にテーブル表示するコードです。
こんな感じで出力されます。

 actor_id | first_name | last_name    | last_update
----------+------------+--------------+------------------------
        1 | Penelope   | Guiness      | 2013-05-26 14:47:57.62
        2 | Nick       | Wahlberg     | 2013-05-26 14:47:57.62
        3 | Ed         | Chase        | 2013-05-26 14:47:57.62
        4 | Jennifer   | Davis        | 2013-05-26 14:47:57.62
        5 | Johnny     | Lollobrigida | 2013-05-26 14:47:57.62
        6 | Bette      | Nicholson    | 2013-05-26 14:47:57.62
        7 | Grace      | Mostel       | 2013-05-26 14:47:57.62
        8 | Matthew    | Johansson    | 2013-05-26 14:47:57.62
        9 | Joe        | Swank        | 2013-05-26 14:47:57.62
       10 | Christian  | Gable        | 2013-05-26 14:47:57.62
(10 行)

なお、データはPostgreSQL tutorialのサンプルデータベースを使いました。
https://www.postgresqltutorial.com/postgresql-sample-database/

public function displayArray(array $rows)
{
    if (!$rows) {
        echo '(0 行)' . PHP_EOL;
        return;
    }

    $col_names = array_keys($rows[0]);
    $max_width = [];

    $col_num = count($col_names);

    // 列名の表示幅を取得する
    for ($i = 0; $i < $col_num; $i++) {
        $max_width[$i] = mb_strwidth($col_names[$i]);
    }

    // 列名とその列のデータの最大の表示幅を調べる
    foreach ($rows as $row) {
        $values = array_values($row);
        for ($i = 0; $i < $col_num; $i++) {
            $val = $values[$i];
            if (mb_strwidth($val) > $max_width[$i]) {
                $max_width[$i] = mb_strwidth($val);
            }
        }
    }

    $lines = [];

    // 列名の表示内容を組み立てる
    $a = [];
    for ($i = 0; $i < $col_num; $i++) {
        $format = '%-' . $max_width[$i] . 's';
        $a[$i] = sprintf($format, $col_names[$i]);
    }
    $lines[] = ' ' . implode(' | ', $a);

    // 仕切り線の表示内容を組み立てる
    $a = [];
    for ($i = 0; $i < $col_num; $i++) {
        // +2は表示時の前後のブランクの分
        $a[] = str_repeat('-', $max_width[$i] + 2);
    }
    $lines[] = implode('+', $a);

    // 各行の表示内容を組み立てる
    foreach ($rows as $row) {
        $values = array_values($row);
        for ($i = 0; $i < $col_num; $i++) {
            $val = $values[$i];
            $space = str_repeat(' ', $max_width[$i] - mb_strwidth($val));
            $values[$i] = is_numeric($val) ? $space . $val : $val . $space;
        }
        $lines[] = ' ' . implode(' | ', $values);
    }

    echo implode(PHP_EOL, $lines) . PHP_EOL;
    echo '(' . count($rows) . ' 行)' . PHP_EOL;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0