我使用PHP / MySQL运行查询并将其编码为JSON,但我不确定如何将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分组为&#34; type,&#34;像这样:
{
"links": [{"source":"58","target":"john","value":"95"},
{"source":"60","target":"mark","value":"80"}],
"nodes":
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
}
非常感谢任何帮助。谢谢!
答案 0 :(得分: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循环条件下执行mysql_num_rows($query)
可能是个问题。值永远不会改变,但PHP必须在每个循环中运行该函数。缓存该值或使用:
while (($row = mysql_fetch_assoc($res)) !== false) { .. }