首页 > 解决方案 > PHP 将多个对象放入 json 文件

问题描述

所以我一直在研究这个 PHP API,它会将 JSON 保存到 PHP 文件中。该代码有效,但只允许 1 个对象。如何在不删除旧 JSON 的情况下添加另一个对象(附加 JSON)

<?php
//-- Parameters --\\
$id = $_GET['id'];
$language = $_GET['language'];
$filter = $_GET['filter'];
$commands = $_GET['commands'];
$name = $_GET['name'];
$members = $_GET['members'];

//-- Read and Parse JSON --\\
$string = file_get_contents("./Data/Guilds.json");
$json_a = json_decode($string, true);

if(isset($json_a[$id])) {

}
else {
    //-- Initialize Array --\\

    $obj[$id] = Array();

    //-- Set Array Objects --\\

    $obj[$id]["language"] = $language;
    $obj[$id]["filter"] = $filter;
    $obj[$id]["commands"] = $commands;

    $obj[$id]["information"]["name"] = $name;
    $obj[$id]["information"]["members"] = $members;

    //-- Encode and Write --\\

    $fp = fopen('./Data/Guilds.json', 'w+');
    fwrite($fp, $json);
    fclose($fp);
}

标签: phpjson

解决方案


推荐阅读