【问题标题】:PHP merge JSON with bracketsPHP用括号合并JSON
【发布时间】:2021-01-21 16:41:37
【问题描述】:

我有这个 JSON 文件:

{"customers": [{"Name": "John Doe", "E-mail": "johndoe@mail.com"}]}

我有这个 PHP 代码:

$customers_file = fopen("customers.json", "r");
$customers = json_decode(fread($customers_file ,filesize("customers.json")), true);
fclose($customers_file);

$customer = array("Name" => "Jane Doe", "E-mail" => "janedoe@mail.com");
        
$customers["customers"] += $customer;

$customers_file = fopen("customers.json", "w");
$customers = fwrite($customers_file, json_encode($customers));
fclose($customers_file);

然后JSON文件转入:

{"customers": [{"Name": "John Doe", "E-mail": "johndoe@mail.com"}, "Name": "Jane Doe", "E-mail": "janedoe@mail.com"]}

有没有办法得到:

{"customers": [{"Name": "John Doe", "E-mail": "johndoe@mail.com"}, {"Name": "Jane Doe", "E-mail": "janedoe@mail.com"}]}

【问题讨论】:

    标签: php json file


    【解决方案1】:

    当你添加新项目时

    $customers["customers"] += $customer;
    

    这是在错误级别添加新数组数据,您需要将其添加到客户数组中(使用[])...

    $customers["customers"][] = $customer;
    

    您还可以查看 file_get_contents()file_put_contents() 以减少 fopen()...fclose() 样板代码。

    【讨论】:

    • 谢谢!但我还有 1 个问题:我得到 致命错误:无法使用 [] 读取
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2015-04-19
    • 2017-02-24
    相关资源
    最近更新 更多