如何解决匿名数组?

how to solve anonymous array?

这是我的 php sql 代码

//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 模板。如果没有建议我如何将这些数据用于我的模板。谢谢。

构建数组时,您需要使用所需的唯一值来设置键。例如:

while($row =mysqli_fetch_assoc($result)) {
    $key = $row['domain'];
    $emparray[$key] = $row;
}

这将导致您的 JSON 被键入 domain 值。

//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"}]}