0

您好我正在尝试查询一个关联数组,其中最终结果应该如下面的这个 json 数组所示。但是我希望数据部分和 id 名称部分为每个节点查询一次,如果一个节点有多个邻接关系,我希望邻接部分查询多次,如果条件是,我如何多次查询这个嵌套数组的一个部分在保持这种结构但节点有多个邻接或没有邻接的同时遇到其余的所有?

   var json =[{
        "adjacencies": [{
           "nodeTo": "graphnode9",
           "nodeFrom": "graphnode5",
           "data": {}
        }],
        "data": {
            "$color": "#C74243",
            "$type": "triangle",
        },
        "id": "graphnode5",
        "name": "graphnode5"
  }];

这是我的数据库结构

nodes                 Relationships                      
-----                 -------------
id int(11),           id int(11),
name varchar(35),     to int(11), //this is the destination node from the id relation 
color varchar(7),     data varchar(0) null
type varchar (12),    Foreign key (id) references nodes(id)
Primary key (id)       

engine = innodb    

这是我获取关联数组的尝试,但它一次查询并复制整个结构。

function getjson(){  
    $db = adodbConnect();
    $query = "SELECT nodes.*, relationships.* FROM nodes inner JOIN relationships ON nodes.id = relationships.id";
    $result = $db -> Execute($query);

    while($row=$result->FetchRow()) {
        $id = (float)$row['id'];
        $name = $row['name'];
        $color1 = $row['color'];
        $type1 = $row['type'];
        $to = (float)$row['to'];

        $array = array(
            "adjacencies:" => array(
                "nodeTo" => "$to",
                "nodeFrom" => "$id",
                "data" => array()
            ),
            "data" => array(
               "$"."color" => $color1,
               "$"."type" => $type1
            ),
            "id".":" => $id,
            "name".":" => $name
        );

    }
    print"$array";
    json_encode($array);
}
4

1 回答 1

1

您需要在循环之外创建数组并向其中添加项目

$array = array();
while($row=$result->FetchRow()) {
    $array[] = array(
        "adjacencies:" => array(
            "nodeTo" => (float)$row['to'],
            "nodeFrom" => (float)$row['id'],
            "data" => array()
        ),
        "data" => array(
           '$color' => $row['color'],
           '$type' => $row['type']
        ),
        "id" => (float)$row['id'],
        "name" => $row['name']
    );

}
于 2013-03-12T20:40:30.870 回答