[英]turn one dimensional array to two dimensional array with loop
我正在尝试将所有SQL表和列拉入数组,应该看起来像这样:
array(
'tableName' => array(
'column1',
'column2',
'column3',
)
);
我编写了这段代码,从数据库中提取表和列的名称并将其推入数组。
<?php
include("db-config.php");
$method = $_SERVER['REQUEST_METHOD'];
$tablesQuery = mysqli_query($link,"SHOW TABLES");
echo '<pre>';
while($table = mysqli_fetch_assoc($tablesQuery)){
$tables[] = $table['Tables_in_'.$DB['database']];
}
for($i = 0;$i<count($tables);$i++){
$currentTable = $tables[$i];
$columnsQuery = mysqli_query($link,"DESCRIBE `".$currentTable."`");
while($column = mysqli_fetch_assoc($columnsQuery)){
$tables[$i][] = $column['Field']; //line 13
}
print_r($currentTable);
}
?>
在第13行,语法tables[$i]
了如何将字符串表示为保持数组,从而阻止了我将列的数据推入内部。
谢谢你们的帮助!
对于此任务,您需要查询INFORMATION_SCHEMA数据库和PDO 以正确的格式获取结果 。
$sql = "SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='$DB[database]'";
$tables = $pdo->query($sql)->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);
将为您提供所需的确切结果。
您没有正确分配数组,因为$tables[$i]
是字符串值而不是数组键:
$currentTable = $tables[$i]; // $tables[$i] is a string: you use it as a string below
mysqli_query($link,"DESCRIBE `".$currentTable."`"); //$currentTable = used as string
然后在while循环中,您尝试使用该字符串作为数组键:
while($column = mysqli_fetch_assoc($columnsQuery)) {
$tables[$i][] = $column['Field']; //$tables[$i] == $currentTable as above = string
您需要做的是使用$ currentTable作为键来分配值:
while($column = mysqli_fetch_assoc($columnsQuery)) {
$tables[$currentTable][] = $column['Field'];
// or
$tables[$i][$currentTable][] = $column['Field'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.