0
我使用PHP連接到我的psql數據庫,並有一些初始代碼連接到數據庫,訪問表並設置列到數組等。但是,我一直在努力獲取我的數據到所需的格式我的代碼已經在運行。我的輸入是Json分層數據格式,如下所示。如何使用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);
?>
這是數據庫表
感謝提前:)