简体   繁体   English

如何解决匿名数组?

[英]how to solve anonymous array?

this is my php sql code 这是我的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);
?>

when I run this code i'm getting an an anonymous json array like this. 当我运行这段代码时,我得到了一个匿名的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"}]

is there a way to give this array a name because without a named array I don't know how to use this json data for dust.js template. 有没有办法给这个数组起个名字,因为没有命名数组,我不知道如何将这个json数据用于ustry.js模板。 If not suggest me how I can use this data for my templating. 如果没有建议我如何使用这些数据进行模板制作。 thank you. 谢谢。

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

Try this. 尝试这个。 Your data will look like this 您的数据将如下所示

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

When building your array, you need to setup your keys using whichever unique value you want. 构建阵列时,需要使用所需的唯一值来设置密钥。 For example: 例如:

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

This will result in your JSON being keyed with the domain value. 这将导致您的JSON使用domain值进行键控。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM