我有一个数据库,里面有一些表和列。我想在PHP中创建一个多维数组来存储这些值。
$tableData = array(array()); // I try to set up the multidimensional array.
/* 1: Get Table Names (works fine) */
$result = mysql_query("SHOW TABLES FROM myDatabase");
$i=0;
while ($row = mysql_fetch_row($result))
{
// Push the table name into the PHP array
array_push($tableData, $row[0]);
}
/* 2: Columns */
for ($i = 1; $i < count($tableNames); $i++)
{
$result = mysql_query("SHOW COLUMNS FROM $tableData[$i]");
while ($row = mysql_fetch_assoc($result))
{
array_push($tableData[$i], $row); // ** ERROR THROWN: first argument must be an array ** //
}
}我该怎么做呢?我觉得这应该很简单,但在过去的4个小时里,我一直在用头敲打键盘和谷歌,试图弄清楚……关于将多维数组放入SQL的教程已经很多了,但反之亦然!
谢谢!
发布于 2011-08-24 14:15:51
您不需要array( array ())来设置多维数组。只需将其他数组作为值推送即可。
试试这个:
foreach ($tableNames as $tableName)
{
$result = mysql_query("SHOW COLUMNS FROM $tableName");
while ($row = mysql_fetch_assoc($result))
{
$tableData[$tableName] = $row;
}
}发布于 2011-08-24 13:54:23
$tableData = array(array());
...
array_push($tableData, $row[0]);
...这只是意味着你最终得到了一个如下所示的数组:
array(array(), 'foo', 'bar', 'baz')你不能像那样“建立一个多维数组”。它应该看起来更像这样:
$tableData = array();
...
array_push($tableData, array($row[0]));
...这样,您将得到一个如下所示的数组:
array(array('foo'), array('bar'), array('baz'))我猜你想要更多类似的东西:
array('foo' => array('col1', 'col2', ...), 'bar' => array('col1', ...))因此,您需要对列执行以下操作:
$result = array();
foreach ($tableNames as $tableName) { // much more useful than for()
$result = mysql_query("SHOW COLUMNS FROM $tableName");
while ($row = mysql_fetch_assoc($result)) {
$result[$tableName][] = $row;
}
}祝你在更多的实验中好运...
var_dump是你的朋友。
发布于 2011-08-24 13:58:35
您对列名的查询不正确。你应该做一些像SHOW COLUMNS FROM mytable FROM mydb;或SHOW COLUMNS FROM mydb.mytable;这样的事情
来源:http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
您可能希望执行以下操作:
$tableData = array();
$result = mysql_query("SHOW TABLES FROM myDatabase");
while ($row = mysql_fetch_row($result))
{
$tableData[$row[0]] = array();
}
foreach ($tableData as $table => $array)
{
$result = mysql_query("SHOW COLUMNS FROM $table FROM myDatabase");
while ($row = mysql_fetch_assoc($result))
{
$tableData[$table][] = $row[0];
}
}尽管我还没有机会运行这段代码来查找错误。
https://stackoverflow.com/questions/7170961
复制相似问题