簡體   English   中英

通過循環將一維數組轉換為二維數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM