繁体   English   中英

如何使用php将数据存储到带有变量名的json.file中

[英]How to store data into json.file with variable name from database using php

我想存储JSON数据store.json文件,如下面的json格式。

store.json

  { "data" :
        [
            {
                "id": 1,
                "customerid": "balaji",
                "name": "Balaji",
                "email": "karurbalamathi@gmail.com",
                "phone": "9566711194"
            }
        ]
    }

但数据存储方式如下

[
  {
    "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);
?>

所以我无法选择要显示的数据。 请帮我解决。

您已在此行添加了data密钥$rows1[] = '{ "data" : '.$rows.'}';

更换

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

与下面

$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);
  • 您必须将其指定为数组的key以获取所需的格式,而不是进行任何字符串操作。

  • 此外, file_exists()unlink()是多余的,因为您在w模式下打开文件。

更改存储数据的方式...

$rows1['data'] = $rows;

当你使用......

$rows1[] = '{ "data" : '.$rows.'}';

$rows是一个数组,所以这不起作用(数组到字符串的转换)。

暂无
暂无

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

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