2016-11-17 127 views
0

我使用PHP/MySQL運行查詢並將其編碼爲JSON,但我不確定如何將JSON導入到我需要的表單中。MySQL到JSON - 結合兩個查詢/格式化

這是我的PHP:

$myquery1 = "select 'links' as type, source, target, value from table"; 

$myquery2 = "select 'nodes' as type, name from table2"; 

$query = mysql_query($myquery1); 

if (! $query) { 
    echo mysql_error(); 
    die; 
} 

$data = array(); 

for ($x = 0; $x < mysql_num_rows($query); $x++) { 
    $data[] = mysql_fetch_assoc($query); 
} 

//(and again for myquery2) 

echo json_encode($data); //not sure how to combine queries here 

我想JSON進行分組由分組 「型,」 像這樣:

{ 
"links": [{"source":"58","target":"john","value":"95"}, 
      {"source":"60","target":"mark","value":"80"}], 
"nodes": 
      [{"name":"john"}, {"name":"mark"}, {"name":"rose"}] 
} 

任何幫助深表感謝。謝謝!

+1

***請[停止使用'mysql_ *'功能(http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions- in-php)。*** [這些擴展](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中刪除。瞭解[prepared](http: //en.wikipedia.org/wiki/Prepared_statement)[PDO]聲明(http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net) /manual/en/mysqli.quickstart.prepared-statements.php)並考慮使用PDO,[這真的很簡單](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

你正在引用''links''和''types'',這將引發語法錯誤 –

+0

@JayBlanchard它不會拋出語法錯誤(對我來說)它只是使所有值的'鏈接'。使用反引號:'\''而不是單引號。 – Halcyon

回答

3

你可以這樣做:

$data = array(
    "links" => array(), 
    "nodes" => array() 
); 
.. 
// for each link 
$data["links"][] = mysql_fetch_assoc($query); 
.. 
// for each node 
$data["nodes"][] = mysql_fetch_assoc($query); 

我認爲mysql_fetch_assoc被它的名字增加了每列兩次,一次一次由它的指數,所以你會希望做一些微調。即:

$row = mysql_fetch_assoc($query); 
$data["links"][] = array(
    "name" => $row["name"], 
    .. etc 
) 

在for-loop條件下做mysql_num_rows($query)可能是一個問題。值永遠不會改變,但PHP必須在每個循環中運行該函數。高速緩存中的值或使用:

while (($row = mysql_fetch_assoc($res)) !== false) { .. } 
+0

這正是我所需要的。謝謝,太平人! – Phoebe