I want to store the JSON data store.json file like below json format.
store.json
{ "data" :
[
{
"id": 1,
"customerid": "balaji",
"name": "Balaji",
"email": "karurbalamathi@gmail.com",
"phone": "9566711194"
}
]
}
But the data is stored like this
[
{
"id": 1,
"customerid": "balaji",
"name": "Balaji",
"email": "karurbalamathi@gmail.com",
"phone": "9566711894"
}
]
php.php
<?php
$json = $conn->prepare("SELECT * from users");
$json->execute();
$json = $json->get_result();
$response = array();
$posts = array();
while ($row = $json->fetch_assoc()) {
$rows[] = $row;
}
$rows1[] = '{ "data" : '.$rows.'}';
print_r($rows1);
$rows = json_encode($rows1);
if(file_exists('data.json')){
unlink('data.json');
}
$myFile = "data.json";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $rows);
fclose($fh);
?>
So I can't select the data for display. Please help me to solve .
You have added data
key yourself in this line $rows1[] = '{ "data" : '.$rows.'}';
.
Replace
$rows1[] = '{ "data" : '.$rows.'}';
print_r($rows1);
$rows = json_encode($rows1);
if(file_exists('data.json')){
unlink('data.json');
}
$myFile = "data.json";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $rows);
fclose($fh);
with below
$json_data = [];
$json_data['data'] = $rows;
$myFile = "data.json";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, json_encode($json_data));
fclose($fh);
You have to assign it as a key
to the array to get the format you desired and not do any string manipulation.
Also, file_exists()
and unlink()
is redundant since you are opening the file in w
mode.
Change the way you store the data to...
$rows1['data'] = $rows;
When you use...
$rows1[] = '{ "data" : '.$rows.'}';
$rows
is an array, so this will not work(array to string conversion).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.