JSON正在覆盖旧数据如何继续使用新ID添加数据

时间:2018-05-29 12:38:41

标签: php json

所以,我正在研究一个应该继续增加ID的JSON文件。但是我遇到了id:0,当我插入新数据时,旧数据将被新数据替换(它保持id:0)。 我不完全确定哪些代码是相关的,什么不相关,所以我会发布我认为应该相关的任何内容,如果有更多与JSON相关的知识的人可以调整(如果需要的话),我会非常感激。

include database_json.php包含以下代码:

$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];

// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
  $data = $_POST;
  //Setup an empty array.
   $errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
    if (count($database['data']) == 0) {
        $ID = 0;
    }
    else {
$maxID = max($database['data']);
        $ID = ++$maxID["id"];
    }
    $newJsonFile = 'jsonData_' . $ID . '.json';
    $newJsonFilePath = 'json_files/' . $newJsonFile;
    //Create new database exercise_txt
    $newArrayData = array(
        'id' => $ID,
         // a lot of variables that aren't related to the problem
    );
 $database['data'][] = $newArrayData;
    file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
    file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
}
else {
    $index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
    $correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
    $newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
    $newJsonFilePath = 'json_files/' . $newJsonFile;
    //Create new database exercise_txt
    $newArrayData2 = array(
        'id' => (int) $_POST['id'],
         // more not related to problem variables
    );
 $database['data'][$index] = $newArrayData2;
    file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
    file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
 echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
编辑:有人希望我发布JSON本身的样子......所以这就是它的样子: 该文件名为:database.json

{"data":[{"id":0,"exercisetitle":"Test300520180924","exerciseWord":["huiswerk"],"syllables":["Huis","werk"],"file":"jsonData_.json","audio":null,"language":null}]}

(不要介意音频和语言,这是以后的事情。

我能做的最好的就是这个,是的,我读过关于发帖的内容以及如何正确格式化等等。但是我经常会说我需要包含某些代码等等,而且大多数情况下会变得凌乱如此地狱,所以我宁愿有太多的代码(我认为相关的代码)然后就没有了。

干杯!

0 个答案:

没有答案