//fetch table rows from mysql db
$sql = "select * from tbl_sample";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$info = json_encode($emparray);
echo $info;
//close the db connection
mysqli_close($connection);
?>
当我运行此代码时,我得到一个像这样的匿名json数组。
[{"id":"1","country":"india","domain":"MBA"},{"id":"2","country":"england","domain":"cricket"},{"id":"3","country":"pakistan","domain":"MTECH"},{"id":"4","country":"newzeland","domain":"bba"}]
有没有办法给这个数组命名,因为没有命名数组我不知道如何将这个json数据用于dust.js模板。如果没有建议我如何使用这些数据进行模板化。谢谢。
答案 0 :(得分:2)
//fetch table rows from mysql db
$sql = "select * from tbl_sample";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$mydata['my_data'] = $emparray;
$info = json_encode($mydata);
echo $info;
//close the db connection
mysqli_close($connection);
试试这个。您的数据将如下所示
{"my_data":[{"id":"1","country":"india","domain":"MBA"},{"id":"2","country":"england","domain":"cricket"},{"id":"3","country":"pakistan","domain":"MTECH"},{"id":"4","country":"newzeland","domain":"bba"}]}
答案 1 :(得分:0)
构建阵列时,您需要使用您想要的任何唯一值来设置密钥。例如:
while($row =mysqli_fetch_assoc($result)) {
$key = $row['domain'];
$emparray[$key] = $row;
}
这将导致您的JSON使用domain
值键入。