dsu5188 2014-01-04 05:08
浏览 218
已采纳

从mysql表中获取数据并将值放在JSONObject中

I am fetching values from mysql table. I am then placing the values inside an array and using th php built function json_enconde to convert these values into a json format. I am getting results back but not in the desired format. In the php code you will notice I am using array and fetching values with a foreach loop to place all values inside. As a result I am getting back several json objects. How can I get back just one json object with the corresponding values?

header("Content-type: application/json");   
$query = $db_con->prepare("SELECT id, name FROM table");
$query->execute();
$data = $course_query->fetchAll();
$json_data = array();
foreach ($data as $row) {
    $json_data[] = array(
       $row["id"] => $row["name"]
    );
}  // foreach ($data as $row) {
echo json_encode($json_data);

Results:

{
1: "Item1"
},
{
2: "Item2"
},
{
3: "Item3"
}

Desired Results:

{
"1":"Item1",
"2":"Item2",
"3":"Item3"
}
  • 写回答

3条回答 默认 最新

  • dongqiu3709 2014-01-04 05:15
    关注

    try this

    foreach ($data as $row) {
    $id=$row["id"];
        $json_data[$id] =$row["name"];
    
    }  
    

    The problem was that while defining the value in json_data in your foreach loop you are creating an array for every single value, so you are not getting the desired result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!