2013-03-30 5 views
2

데이터베이스에서 json 배열로 데이터를 쿼리하여 궁극적으로 javascript에서 강제로 유도 된 그래프를 생성하려고합니다. 여기에 Json 배열이 있어야합니다. 그러나 노드는 다중 인접성을 갖거나 전혀 가질 수 없습니다. 인접성 섹션이 노드마다 다르며 노드의 인접성 수에 따라 조정할 수있는 json 배열을 쿼리하려면 어떻게해야합니까?복잡하게 중첩 된 배열 문제

Var JSON =[ 
{ 
    "adjacencies": [ 
    { 
     "nodeTo": "graphnode9", 
     "nodeFrom": "graphnode5", 
     "data": {} 
    } 
    ], 
    "data": { 
    "$color": "#416D9C", 
    "$type": "star" 
    }, 
    "id": "graphnode5", 
    "name": "graphnode5" 
}, 
]; 

하거나

Var JSON =[ 
{ 
    "adjacencies": [ 
    { 
     "nodeTo": "graphnode9", 
     "nodeFrom": "graphnode5", 
     "data": {} 
    }, 
    { 
     "nodeTo": "graphnode9", 
     "nodeFrom": "graphnode5", 
     "data": {} 
    }, 
    { 
     "nodeTo": "graphnode9", 
     "nodeFrom": "graphnode5", 
     "data": {} 
    } 
    ], 
    "data": { 
    "$color": "#416D9C", 
    "$type": "star" 
    }, 
    "id": "graphnode5", 
    "name": "graphnode5" 
}, 
]; 

을 가질 수 또는 그들이 가지고 수없는

Var JSON =[ 
{ 
    "adjacencies": [], 
    "data": { 
    "$color": "#416D9C", 
    "$type": "star" 
    }, 
    "id": "graphnode5", 
    "name": "graphnode5" 
}, 
]; 

여기 내 시도는 지금까지, 그러나 이것은 단지 하나 개의 인접를 할 수있는 JSON을 생산, 노드가 가지고있는 인접성의 수를 조정할 Json 쿼리를 어떻게 설정할 수 있습니까? 데이터 및 ID 섹션을 한 번만로드하지만 adjacenies를 다양하게 만들 수 있습니까? 여기

는 단일 쿼리의 결과를 반환하려면

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['goingto']; 
    $thumb =$row['thumb']; //image path 

    $array[] = array(
    "adjacencies" => array(array(
    "nodeTo" => "$to", 
    "nodeFrom" => "$id", 
    "data" => array())), 
    "data" => array(
    "$"."color" => $color1, 
    "$"."type" => $type1), 
    "id" => $id, 
    "name" => "<img src='".$thumb."' height='25' width='25' alt='root'/><label>".$name."</label>"); 
} 

$json = json_encode($array); 
print "$json"; 
//return $json; 
} 
+0

당신은 결코 인접성의 빈 목록을 얻지 못한다는 것을 의미합니까? 그게 문제라면 LEFT JOIN을 사용하십시오. – bfavaretto

+0

모든 것이 제대로로드되지는 않지만 각 노드에 대한 ID 및 데이터 배열을 한 번로드하지만 over all all array의 구조를 유지하면서 인접성을 여러 번 가져야합니다. – user1902588

+0

@ user1902588이 질문에 3 번 질문 한 것으로 보입니다. 이 하나, 그리고 [여기] (http://stackoverflow.com/questions/15608156/array-with-multiple-sizes-query-from-database-issue) 및 [여기] (http://stackoverflow.com/questions/15714467/multideminsional-array-query-iteration-issue). 그 마지막 하나는 닫혔다. 그리고 나는 대답/코멘트 등이없는 것뿐만 아니라 닫힌 다른 하나를 추천 할 것이다. – Sepster

답변

2

가, 다음에 대한 중복 된 데이터로 끝날 것입니다 나의 시도가 여기 내 데이터베이스 구조

nodes     Relationships      
-----     ------------- 
id int(11),   id int(11), 
name varchar(35), goingto 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  

이며, 해당 노드와 별개의 인접성이있는 각 개별 행에있는 노드 ... 어느 것이 좋습니다, 그것이 작동하는 방법입니다.

INNER join을 사용했기 때문에 해당 노드에 인접성이없는 경우 노드가 반환되지 않습니다. 관련 인접성 테이블의 결과가없는 노드를 포함하려면 LEFT join을 사용해야합니다. .

노드별로 정렬하면 id으로 모든 노드와 그 인접성이 함께 그룹화되어 나타납니다. 이것은 아마도 id이 당신의 pk이며, 따라서 이런 식으로 "자동적으로"일어나기 때문에 이미 일어난 것입니다. 그러나 ORDER BY nodes.id은 이러한 일이 일어날 수 있도록 보장하며, 코드를 보는 사람이라면 누구나 자신의 의도를 분명히 알 수 있습니다.

두 테이블에서 모두 *을 반환하기 때문에 node.idrelationship.id에 열 이름 충돌이 발생합니다. PHP에서 예측 가능한 결과를 얻을 수 있도록 열을 명시 적으로 지정하면이 문제를 피할 수 있습니다.

SELECT 
    n.id as n_id, 
    n.name, 
    n.color, 
    n.type, 
    r.id as r_id, 
    r.goingto, 
    r.data 

FROM 
    nodes n 

    LEFT JOIN relationships r 
    ON n.id = r.id 

ORDER BY 
    n.id 

이 같은 뭔가를 보이는 결과 집합을 반환 :

그래서 SQL은 더 같이 할 수

n_id | name | color | type | r_id | goingto | data 
------+-------+--------+-------+------+---------+----------- 
1  | node1 | red | type1 | 1 | 5  | stuff 
1  | node1 | red | type1 | 2 | 6  | morestuff 
2  | node2 | blue | type2 | 3 | 10  | whatever 
3  | node3 | green | type3 | null | null | null 
4  | node4 | orange | type4 | 4 | 20  | xxx1 
4  | node4 | orange | type4 | 5 | 21  | xxx2 
4  | node4 | orange | type4 | 6 | 22  | xxx3 

etc... 

(즉,이 노드 2 일을 가지고, 노드 1은 두 개의 관계를 맺고 가정 노드 3은 관계가 없으며 노드 4는 3을가집니다.

그리고 배열을 만드는 코드는 현재 레코드의 노드가 이전 노드와 동일하지 않은 경우에만 결과를 반복하고 새로운 노드를 작성하면됩니다 (즉, ORDER BY node.id을 "수집 "특정 노드에 대한 모든 정보, 순차적으로).

이 코드는 테스트되지 않았지만 의도는 분명하다고 생각합니다. 필요에 따라이 코드를 구부릴 수 있어야합니다. 그러나 기본적으로 위 코드를 구현합니다.

while 루프를이 모든 것으로 교체하십시오. 이 "널 (null)"또는 무엇을 할 것인지, 즉 -

$previd = -1; 
while($row=$result->FetchRow()) 
{ 
    $id= (float)$row['n_id']; // <--- note change from 'id' to 'n_id' 
    $name = $row['name']; 
    $color1 = $row['color']; 
    $type1 = $row['type']; 
    $to= (float)$row['goingto']; 
    $thumb =$row['thumb']; //image path 

    // Is this row the start of a new node?  
    if ($previd != $id) { 
     // Yes, new node. Record our new node id, for future new node checks. 
     $previd = $id; 

     // Store the previous node we've already built, now that it's complete (but only if there was a previous node!) 
     if ($previd != -1) { 
      $array.push($node); 
     } 

     // Start our new node off, ready to accept adjacencies 
     $node = array(
      "adjacencies" => array(), 
      "data" => array(
        "$"."color" => $color1, 
        "$"."type" => $type1 
       ), 
      "id" => $id, 
      "name" => "<img src='".$thumb."' height='25' width='25' alt='root'/><label>".$name."</label>"); 
    } 

    // Any adjacency for this node, on this row? 
    if ($to != null) { // <-- Not sure about this line! 
     // Yes there is, so create the new adjacency record and add it to the current node's adjacency array. 
     $node["adjacencies"].push(
      array(
       "nodeTo" => "$to", 
       "nodeFrom" => "$id", 
       "data" => array() 
      ) 
     ); 
    } 
} 

나는 "더 인접는"$to에 표시되지 않습니다 방법을 잘 모르겠어요. 나는 당신에게 그것을 시험 할 것이지만 줄에 이것을 반영 할 필요가 있다고 말하면 충분할 것입니다. if ($to != null) { // <-- Not sure about this line!

+0

sepster 당신은 SQL 문에 관한이 발췌문에서 내 데이터베이스 이론 교사에 대해 더 많이 가르쳐 주었다. 당신의 도움에 진심으로 감사드립니다. – user1902588

+0

@ user1902588 내 기쁨 친구, 정말 유용하다고 생각되어서 기쁩니다. 동의 해 주셔서 감사합니다. 정말 고맙습니다. – Sepster