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

时间:2014-10-30 16:55:05

标签: php json pdo

我有这个数据库:

enter image description here

我需要使用php pdo获取此JSON输出:

{
    "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",
        }
    ]
}

因为你可以看到我需要在JSON编码之前修改数据......我需要添加一些html和css。

我试着这样做:

/* 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);

这不会像我上面那样呈现正确的JSON格式。

更新:

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 个答案:

答案 0 :(得分:0)

现在您正在覆盖$temp变量而不使用它。您需要将$output = ['data' => $temp];移动到foreach循环中并稍微更改一下:

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 :(得分:0)

您在循环的每次迭代中都会覆盖$temp数组。你可能想要:

foreach($result as $r) {
    $temp[] = array(....);
         ^^---array push shorthand;
}

代替。