您好我正在尝试查询一个关联数组,其中最终结果应该看起来像下面的这个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);
}
答案 0 :(得分: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']
);
}