在PHP中,如何在表中显示数组内容

时间:2011-04-06 12:50:07

标签: php mysql ascii-art

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

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)数组?

以下是代码用法示例:

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

3 个答案:

答案 0 :(得分:1)

非pdo接近:)

function renderMySQLTable($query) {
  echo `mysql -H -e"$query"`;
}

对于阵列来说并不难。几个循环,你有你需要的。 从运行print_r($arr)开始,看看它的结构

答案 1 :(得分:1)

接近 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;
}

答案 2 :(得分:0)

使用Table,并在css中给出一些样式。

echo "<table class='datasheet'>";
foreach($arr as $a)
{
    echo "<tr>";
        foreach($a as $v)
        {
                echo "<td>$v</td>";
        }
    echo "</tr>";
}
echo "</table>";