试图用PHP插入json

时间:2021-01-18 15:43:01

below i have my json structure, what i'm trying to do at the moment, is insert new fields, with their own values, and i can't think of a way to do this in php. so far i have :

下面我有我的json结构,我现在正在尝试做的是插入新的字段,有自己的值,我想不出在php中这样做的方法。到目前为止我有:

//read the json file contents
$jsondata = file_get_contents('sleaderboard.json');

//convert json object to php associative array
$outdata = json_decode($jsondata, true);

$encdata = json_encode($indata);
$uname = $_POST["username"];

$indata = $uname . '{' . $encdata . '}';

file_put_contents('sleaderboard.json', $indata);
?>

which seems to almost work, but deletes the old data. anybody got help? PS: $indata is just elements passed through post, collected earlier in the code.

这几乎可以工作,但删除旧数据。有人得到帮助吗? PS:$ indata只是通过帖子传递的元素,在代码的前面收集。

{
    "clarke": {
        "name": "clarke",
        "comment": "comments test",
        "score": 6
    },
    "sam": 
    {
        "name": "sam",
        "comment": "insert regular comment here",
        "score": 0
    },
    "test":
    {
        "name": "test",
        "comment": "boring, normal, extremely generic comment",
        "score": 7
    }
}

1 个解决方案

#1


0  

From my understanding you want to append into file.

根据我的理解,你想要附加到文件中。

file_put_contents('sleaderboard.json', $indata, FILE_APPEND);

#1


0  

From my understanding you want to append into file.

根据我的理解,你想要附加到文件中。

file_put_contents('sleaderboard.json', $indata, FILE_APPEND);