dongzuan4860 2014-10-30 16:55
浏览 281
已采纳

从mysql数据库以正确的方式格式化JSON

I have this database:

enter image description here

I need to get this JSON output with php pdo:

{
    "data": [
        {
            "ID": "<div class=\"btn btn-danger\">1</div>",
            "naziv": "some data from database",
            "vrsta": "some data from database",
        },
        {
            "ID": "<div class=\"btn btn-danger\">2</div>",
            "naziv": "some data from database",
            "vrsta": "some data from database",
        }
    ]
}

So as you can see I need to modify data before JSON encoding...I need to add some html and css.

I try to do this with:

/* select all the weekly tasks from the table googlechart */
$result = $db->prepare('SELECT ID,naziv,vrsta FROM investicije');
$result->execute();

/* Extract the information from $result */
foreach($result as $r) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp['ID'] = '<div class="btn btn-danger">'.$r['ID'].'</div>'; 
    $temp['vrsta'] = $r['vrsta'];
    $temp['naziv'] = $r['naziv'];
}

$output = ['data' => $temp];
$jsonTable = json_encode($output);

This does not render the right JSON format as I put above.

UPDATE:

JS:

$(document).ready(function() {
    $('#example').dataTable( {
        "ajax": "table1.php",
        "columns": [
            { "data": "ID" },
            { "data": "naziv" },
            { "data": "vrsta" },

        ]
    } );
} );

HTML

<div class="container">
<table id="example" class="table table-striped table-bordered table-responsitive" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>ID</th>
                <th>Naziv</th>
                <th>Vrsta</th>

            </tr>
        </thead>

        <tfoot>
            <tr>
               <th>ID</th>
                <th>Naziv</th>
                <th>Vrsta</th>
            </tr>
        </tfoot>
    </table>
    </div>
  • 写回答

2条回答 默认 最新

  • duande1986 2014-10-30 17:03
    关注

    Right now you are overwriting your $temp variable without using it. You need to move $output = ['data' => $temp]; into the foreach loop and change it a bit:

    foreach($result as $r) {
        $temp = array();
        // the following line will be used to slice the Pie chart
        $temp['ID'] = '<div class="btn btn-danger">'.$r['ID'].'</div>'; 
        $temp['vrsta'] = $r['vrsta'];
        $temp['naziv'] = $r['naziv'];
    
        $output['data'][] = $temp;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP