简体   繁体   中英

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:

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.

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 .

$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:

$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($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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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