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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器