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

将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 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败
  • ¥150 计算DC/DC变换器平均模型中的参数mu
  • ¥25 C语言代码,大家帮帮我
  • ¥15 请问以下文字内容及对应编码是用了什么加密算法或压缩算法呢?
  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)