Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将mysql查询返回的数据转换为json(基于树)_Javascript_Php_Mysql_Json - Fatal编程技术网

Javascript 将mysql查询返回的数据转换为json(基于树)

Javascript 将mysql查询返回的数据转换为json(基于树),javascript,php,mysql,json,Javascript,Php,Mysql,Json,这个问题之前也有人问过,但我想没有人回答 假设mysql查询返回如下结果 name | id tarun | 1 tarun | 2 tarun | 3 现在,如果我们使用标准json编码,我将得到如下结果: [{"name":"tarun","id":"1"},{"name":"tarun","id":"2"},{"name":"tarun","id":"3"}] 但我的输出如下 [{"name" : "tarun", "ids" : [{"id": "1

这个问题之前也有人问过,但我想没有人回答

假设mysql查询返回如下结果

name    |  id
tarun   |   1
tarun   |   2
tarun   |   3 
现在,如果我们使用标准json编码,我将得到如下结果:

[{"name":"tarun","id":"1"},{"name":"tarun","id":"2"},{"name":"tarun","id":"3"}]
但我的输出如下

[{"name" : "tarun", "ids" : [{"id": "1"},{"id": "2"},{"id": "3"}]}]
请忽略我的语法错误(如果有),但我希望我的问题有意义。
我正在使用PHP作为我的后端脚本语言。

您可能正在执行类似的操作

SELECT name, id FROM ...

根据你想要的结构,你会想要

   $data[$row['name']]['ids'][] = array('id' => $row['id']);

这不会给出确切的结构,但会将所有ID作为子数组放在由
tarun
字段值键入的数组下。

扩展@Marc B的答案

// Getting per person id's list
$people = array();
while ($row = mysql_fetch_assoc($result)) {
    $people[$row['name']][] = array('id' => $row['id']);
}

// Encoding as JSON
$output = "[";

foreach ($people as $name => $ids) {
    $output .= '{"name" : "'.$name.'", ids: [';
    foreach ($ids as $key => $id) {
        $output .= '{"id" : "'.$id.'"},';
    }
    rtrim($output, ",");
    $output .= ']},';
}
rtrim($output, ",");
$output .= ']';

echo $output;

上面的解决方案是针对这个问题的。在我看来,针对这个问题的通用JSON编码方法是非常困难的,或者说是不可能的。

我建议使用按名称排序的方法进行查询,然后在读取行时,只需进行简单检查,看看$row['name']是否已更改,如果已更改,请将收集的id添加到php对象中

$curName="";
$curIds=array();
$betterJ=array();
$result = mysql_query ("SELECT name,id FROM mytable WHERE 1 ORDER BY NAME);
while($row=mysql_fetch_array($result)
{
    if($curName=="")
        $curName=$row['name']

    if($row['name']!=$curName){
        $betterJ[]=array($name=>$curName,$ids=>$Ids)
        $curName=$row['name']
        $curIds=array()
    }
    $Ids[]=$row['id];
}
$betterJ[]=array($name=>$curName,$ids=>$Ids);
echo json_encode($betterJ);
这可能是我在这里写的错别字或其他东西,但它应该产生类似json的内容

[ [name:"tarus1",ids:[1,2,3]], [name:"tarus2",ids:[4,5,6], ... ]  
你可以在html等的模板中使用它

[ [name:"tarus1",ids:[1,2,3]], [name:"tarus2",ids:[4,5,6], ... ]