【问题标题】:How to create hierarchical json using data from a psql database?如何使用 psql 数据库中的数据创建分层 json?
【发布时间】:2013-04-17 22:04:37
【问题描述】:

我正在使用 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);

?>

这是数据库表的格式

提前致谢:)

【问题讨论】:

    标签: php json hierarchical-data psql


    【解决方案1】:

    我只是为你编码一个圆顶。你需要检查你自己

    $dbh = pg_connect("host=localhost dbname=sample user=postgres");
    
    $ret = array();
    $ret['name'] = 'data';
    $ret['children'] = get_chilren($dbh,0);
    
    return  json_encode($ret);
    
    
    while ($line = pg_fetch_array($result)) {
    
    }
    
    
    function get_chilren($dbh,$parentid){
      var $cret = array();
      $sql = "select * from database where parentid=".$parentid
      $cresult = pg_query($dbh, $sql);
      if (!$cresult) {
        echo "An error occured.\n";
        exit;
      }
      while($chil = pg_fetch_array($cresult)){ // fetch each row
        $cret['name'] = $chil['name'];
        $cc = get_chilren($dbh,$chil['id']);
        if(is_array($cc)) 
        {//when it hava a child
          $cret['children'] = $cc;
        }else{ //not hava
          $cret['order'] = $chil['order'];
        }
      }
      return $cret;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-26
      • 2021-03-21
      • 2018-11-08
      • 1970-01-01
      • 2012-10-25
      • 2022-07-15
      • 1970-01-01
      • 2019-10-01
      • 2013-01-20
      相关资源
      最近更新 更多