dsbifvcxr458755493 2018-06-04 08:22
浏览 39

JSON增量不起作用

I am working on a JSON file in which I want to increment instead of overwriting the data. However I cannot seem to do this (since it keeps on overwriting instead of adding data with an incremented ID).

The code underneath is: database_json.php (as u can see I include it in saveJson.php)

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

the below is the code of the file saveJson.php contains the following code:

// 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);
}

so, what I wish for: To increment the IDs and NOT to overwrite the data. I already did some research and didn't find any useful information besides this --> Auto increment id JSON, but to me it looks like I have the same principle applied.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 公交车和无人机协同运输
    • ¥15 stm32代码移植没反应
    • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
    • ¥100 连续两帧图像高速减法
    • ¥15 如何绘制动力学系统的相图
    • ¥15 对接wps接口实现获取元数据
    • ¥20 给自己本科IT专业毕业的妹m找个实习工作
    • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
    • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
    • ¥50 mac mini外接显示器 画质字体模糊