how to solve anonymous array?

272 views Asked by At

this is my php sql code

//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.

[{"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. If not suggest me how I can use this data for my templating. thank you.

2

There are 2 answers

0
Parveen Chauhan On BEST ANSWER
//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"}]}
0
Jeremy Harris On

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.