[英]Querying nested associative array from database issue
嗨,我正在尝试查询一个关联数组,最终结果应类似于下面的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);
}
您需要在循环外创建数组并向其中添加项目
$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']
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.