2016-11-17 135 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