doutui8842 2014-12-10 17:36
浏览 2030
已采纳

将mysql select结果转换为json(数组数组)

I need to encode a table content to JSON in order to insert it into a file.

The output has to be as following :

{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}

Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.

The only thing I could manage for the moment is this :

      $return_arr = array();
$sql = "SELECT * FROM bo_appart"; 
$result = mysql_query($sql) or die(mysql_error());

$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
 $index++;
}

echo json_encode($return_arr);

And here is the output I get :

[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]

Thanks a lot !!!

UPDATED

Working code :

$return_arr = array();
$sql = "SELECT * FROM bo_appart"; 
$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}

echo json_encode($return_arr);

}

  • 写回答

4条回答 默认 最新

  • doujianwei8217 2014-12-10 17:46
    关注

    This loop is enough, to create the desired JSON:

    $return_arr = array();
    while ($row = mysql_fetch_assoc($result)) {
        $return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
    }
    echo json_encode($return_arr);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题