【发布时间】:2017-07-31 18:42:16
【问题描述】:
我正在尝试使用 jstree 创建一棵树,它将显示特定数据库的所有表沿表的列。
现在这是我的脚本,我使用它首先从数据库中获取表名,然后使用该表名来获取该表中可用的所有列。
<?php
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$post_data = array('id' => $dbname,'text' => $dbname, 'children' => array());
//echo "Connected successfully";
$sql = "SHOW tables";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$new = array();
array_push($new, array("id" => $row['Tables_in_test'], "text" => $row['Tables_in_test'], "children" => array()));
$sql1 = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".$dbname."' AND TABLE_NAME = '".$row['Tables_in_test']."'";
$result1 = $conn->query($sql1);
while($row1 = $result1->fetch_assoc()) {
array_push($new[0]['children'], array("id" => $row1['COLUMN_NAME'], "text" => $row1['COLUMN_NAME']));
}
array_push($post_data['children'], $new);
}
} else {
echo "0 results";
}
print_r(json_encode($post_data));
$conn->close();
?>
现在,我通过以下方式获取数据:
{
"id": "test",
"text": "test",
"children": [
[
{
"id": "accounts",
"text": "accounts",
"children": [
{
"id": "id",
"text": "id"
},
{
"id": "name",
"text": "name"
}
]
},
{
"id":"accounts_cases",
"text":"accounts_cases",
"children":[
{
"id":"id",
"text":"id"
},
{
"id":"account_id",
"text":"account_id"
}
]
}
],
],
}
现在,这种格式的数据不适用于jstree。如您所见,第一个children 是一个数组,但由于脚本,它以某种方式将数组显示为数组。是这样的:
"text": "test",
"children": [
[
"id": "accounts",
应该是这样的:
"text": "test",
"children": [
"id": "accounts",
这个我不知道怎么解释,但是应该是这样才能正常工作:
{
"id": "sugarcrm",
"text": "sugarcrm",
"children": [
{
"id": "accounts",
"text": "accounts",
"children": [
{
"id": "id",
"text": "id"
},
{
"id": "name",
"text": "name"
}
]
},
{
"id":"accounts_cases",
"text":"accounts_cases",
"children":[
{
"id":"id",
"text":"id"
},
{
"id":"account_id",
"text":"account_id"
}
]
}
],
}
我知道我的脚本有问题,但我无法更正。所以,请在这里帮助我。
【问题讨论】:
-
我对php不太熟悉,但也许你可以试试array_merge这一行?
array_push($post_data['children'], $new);stackoverflow.com/questions/4268871/… -
不,它不工作。如链接中所述,如果数组具有字符串格式的键,这将不起作用。它将覆盖前一个。而那件事正在发生。
-
也许您可以使用
array_push推入另一个数组(而不是直接推入'children'),然后在while 循环结束后使用array_merge。目前似乎它正在尝试将数组推入子数组中,而不是将其添加为元素。
标签: php mysql json jstree array-push