在PHP中,如何在表格中显示数组内容 [英] In PHP, how to display array contents in a table

查看:252
本文介绍了在PHP中,如何在表格中显示数组内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在MySQL客户端中进行选择,我将得到如下所示的输出:

If I do a select in the MySQL client, I will have output that looks like this:

mysql> select * FROM `group` LIMIT 2;
+----------+---------------------+-----------------+-------------+
| group_id | group_supergroup_id | group_deletable | group_label |
+----------+---------------------+-----------------+-------------+
|        1 |                   4 |               0 | defaut      |
|        8 |                   1 |               1 | dbdfg       |
+----------+---------------------+-----------------+-------------+

如何在这样的表中转换PDO fetch(或fetchAll)数组?

How can I convert a PDO fetch (or fetchAll) array in a table like that?

这是一个代码用法示例:

Here's a code usage example:

$prep = $pdo->query('SELECT * FROM `group` LIMIT 2;');
$arr = $prep->fetchAll(PDO::FETCH_ASSOC);
echo renderMySQLTable($arr);

推荐答案

类似于 mysql客户端输出的内容:

$data = array(
    array(
        'group_id'            => '1',
        'group_supergroup_id' => '4',
        'group_deletable'     => '0',
        'group_label'         => 'default',
    ),
    array(
        'group_id'            => '8',
        'group_supergroup_id' => '1',
        'group_deletable'     => '1',
        'group_label'         => 'dbdfg',
    ),
);

if ( empty($data) ) {
    echo "Empty set";
} else {
    // determine widths of titles
    $colWidths = array();
    foreach ( $data[0] as $title => $value ) {
        $colWidths[$title] = strlen($title);
    }
    // determine widths of columns
    foreach ( $data as $row ) {
        foreach ( $row as $title => $value ) {
            if ( is_null($value) ) {
                $value = 'NULL';
            }
            if ( $colWidths[$title] < strlen($value) ) {
                $colWidths[$title] = strlen($value);
            }
        }
    }
    // generate horizontal border
    $horizontalBorder = '+';
    foreach ( $colWidths as $title => $width ) {
        $horizontalBorder .= str_repeat('-', $width + 2) . "+";
    }
    $horizontalBorder .= "\n";
    // print titles
    echo $horizontalBorder;
    echo '|';
    foreach ( $data[0] as $title => $value ) {
        printf(" %-{$colWidths[$title]}s |", $title);
    }
    echo "\n";
    echo $horizontalBorder;
    // print contents
    foreach ( $data as $row ) {
        echo "|";
        foreach ( $row as $title => $value ) {
            if ( is_null($value) ) {
                $value = 'NULL';
            }
            printf(" %-{$colWidths[$title]}s |", $value);
        }
        echo "\n";
    }
    echo $horizontalBorder;
}

这篇关于在PHP中,如何在表格中显示数组内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆