简体   繁体   English

通过循环将一维数组转换为二维数组

[英]turn one dimensional array to two dimensional array with loop

I'm trying to pull out all SQL tables and column into array, should look like this: 我正在尝试将所有SQL表和列拉入数组,应该看起来像这样:

array(
 'tableName' => array(
      'column1',
      'column2',
      'column3',
  )
);

I have wrote this code that pull tables and columns names from the database and push it to array. 我编写了这段代码,从数据库中提取表和列的名称并将其推入数组。

<?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);
    }
?>

on line 13 the syntax tables[$i] some how turn into string instand of staying array, so that stopped me from pushing columns's data inside. 在第13行,语法tables[$i]了如何将字符串表示为保持数组,从而阻止了我将列的数据推入内部。

Thank for your guys help! 谢谢你们的帮助!

For this task you need to query the INFORMATION_SCHEMA database and PDO to get the result in the proper format . 对于此任务,您需要查询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);

will give you the exact result you want. 将为您提供所需的确切结果。

You are not assigning the array correctly because $tables[$i] is a string value and not an array key: 您没有正确分配数组,因为$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

Then in your while loop, you attempt to use that string as an array key: 然后在while循环中,您尝试使用该字符串作为数组键:

while($column = mysqli_fetch_assoc($columnsQuery)) {
    $tables[$i][] = $column['Field']; //$tables[$i] == $currentTable as above = string

What you need to do instead is assign the value using $currentTable as the key: 您需要做的是使用$ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM