如何使用 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);
?>

所以我无法select显示数据。 请帮我解决。

将数据存储方式更改为...

$rows1['data'] = $rows;

当您使用...

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

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

您已在此行添加 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 模式下打开文件。