dqb14659 2015-12-29 01:21
浏览 39
已采纳

改变JSON格式php

I have this php code that i need to change the JSON format i get the data from a mysql db:

// Retrieve data from database 
    $sql="SELECT nombre FROM deudores ORDER BY fecha ASC LIMIT 10";
    $result=mysqli_query($con, $sql);

    $emparray = array();
    // Start looping rows in mysql database.
    while($rows=mysqli_fetch_assoc($result)){
        $emparray[] = $rows;
    // close while loop 
    }
    //print_r($emparray);
    //echo json_encode($emparray);
    $output = array(
   'c2array' => true,
   'size' => array(
       0 => count($emparray),
       1 => 1,
       2 => 1
   ),
   'data' => array()
    );

    $x = 0;
    foreach ($emparray as $value) {
   $output['data'][$x] = array();
   $output['data'][$x][0] = array();
   $output['data'][$x][0][0] = $value;
   $x++;
    }

    echo json_encode($output);

That code print this JSON:

{"c2array":true,"size":[7,1,1],"data":[[[{"nombre":"test"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"test"}]],[[{"nombre":"test"}]],[[{"nombre":"oscar"}]],[[{"nombre":"Oscar"}]]]}

but i need the JSON to look like this:

{"c2array":true,"size":[7,1,1],"data":[[[test]],[[Oscar]],[[Oscar]],[[test]],[[test]],[[oscar]],[[Oscar]]]}

How can i achive this?

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • doumeng1143 2015-12-29 01:36
    关注

    Use mysql_fetch_row() instead of mysql_fetch_assoc.

    while($rows=mysqli_fetch_row($result)){
        $emparray[] = $rows;
    // close while loop 
    }
    

    And just set $emparray as value for $output['data']. No need extra work!

    $output['data'] = $emparray;
    

    This should make the output like this :

    {"c2array":true,"size":[7,1,1],"data":[["test"],["Oscar"],["Oscar"],["test"],["test"],["oscar"],["Oscar"]]}  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)