我正在使用 php 连接到我的 psql 数据库,并有一些初始代码来连接到数据库、访问表并将列设置为数组等。但是,我一直在努力将我的数据转换为我想要的格式代码已经在运行。我的输入是 Json 分层数据形式,如下所示。
function getData() {
return {
"name": "data",
"children": [
{
"name": "America",
"children": [
{
"name": "MA",
"children": [
{"name": "Westborough", "order": 30},
{"name": "Southborough", "order":20}
]
},
{
"name": "NH",
"children": [
{"name": "Nashua", "order": 12}
]
},
{
"name": "CA",
"children": [
{"name": "SanFransico", "order": 17}
]
}
]
}
]
};
这是我目前使用 php 的代码:
<?php
// attempt a connection
$dbh = pg_connect("host=localhost dbname=sample user=postgres");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM dataset";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
//Sets the column at 1 to an array
$arr = pg_fetch_all_columns($result, 1);
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
这是数据库表的格式
提前致谢 :)