以json格式引导数据表动态传递表头

时间:2016-08-03 11:23:06

标签: php json

我正在从json数据创建数据表。表数据正在变好。现在我想用这些json数据传递表头。

我的data.php

<?php
include('config/db_i.php');
$sql_sel = mysqli_query($con,"SELECT * FROM `tbl`");
$array = array();
$array['data'] = array();

while($res_sel = mysqli_fetch_row($sql_sel)){
    $array['data'][] = $res_sel;
}
echo json_encode($array);
?>

现在输出就像

{"data":[["1","John","USA"],["2","BOB","INDIA"],["3","James","UK"],["4","Dani","CHINA"]]}

我也希望传输列值...即ID,名称,国家/地区

1 个答案:

答案 0 :(得分:0)

您需要使用mysqli_fetch_assoc()而不是mysqli_fetch_row()从数据库中获取关联数组。然后,您将收到一个JSON对象,其属性是列名,而不是数组。另外,我建议使用JSON_NUMERIC_CHECK option来确保数字传递。

<?php
include("config/db_i.php");
$array = array("data"=>array());
$sql_sel = $con->query("SELECT * FROM tbl");
if ($sql_sel) {    
    while($res_sel = $sql_sel->fetch_assoc()){
        $array['data'][] = $res_sel;
    }
}

header("Content-Type:application/json");
echo json_encode($array, JSON_NUMERIC_CHECK);

这应该是这样的:

{"data":[{"id":1,"name":"John","country":"USA"},{"id":2,"name":"BOB","country":"INDIA"},{"id":3,"name":"James","country":"UK"},{"id":4,"name":"Dani","country":"CHINA"}]}