【问题标题】:adding to json file instead of adding changes data添加到 json 文件而不是添加更改数据
【发布时间】:2019-10-17 18:25:35
【问题描述】:

我有一个实现写入 json 文件的方法,

public function setJsonContent(array $data): void
{
    if (file_exists('data/db.json')) {
        $content = $this->getJsonContent();
        if ($content) {
            $data = array_merge($data, $content);
        }
    }
    file_put_contents('data/db.json', json_encode($data));
}

它还有一个方法可以从中获取这个文件和数据。

public function getJsonContent()
{
    $json = file_get_contents('data/db.json');
    return json_decode($json, true);
}

在另一个类中,我有一个从用户接收数据并写入的方法

    $userName = $input->getUserInput('Please, enter user name: ');
    $group = $input->getUserInput('Please, enter group: ');
    $age = $input->getUserInput('Please, enter age: ');

    $this->getJson()->setJsonContent([ $userName => $group, 'age' => $age ]);

第一次运行会写

Please, enter user name: qqq
Please, enter group: www
Please, enter age: eee

{"qqq":"www","age":"eee"}

下一次运行会写

Please, enter user name: aaa
Please, enter group: sss
Please, enter age: ddd

{"aaa":"sss","age":"eee","qqq":"www"}

问题:如何构造数据记录,以便像

{
  "name": [
    "group",
    "age"
  ],
  "name2": [
    "group",
    "age"
  ]
}

【问题讨论】:

    标签: php arrays json oop data-structures


    【解决方案1】:

    您只需要更改您传递的数据的结构,使其成为一个数组,其名称作为具有组和年龄的子数组的键(最后两个没有键)...

    $this->getJson()->setJsonContent([ $userName => [$group, $age ]]);
    

    【讨论】:

    • 谢谢你,你需要什么,你不知道如何缩进,否则现在保存就一行
    • 现在{"qqq2":["www2","eee2"],"qqq":["www","eee"]}
    • 只需将JSON_PRETTY_PRINT 添加到file_put_contents('data/db.json', json_encode($data, JSON_PRETTY_PRINT));
    猜你喜欢
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2022-01-22
    • 2022-07-13
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多