如何通过更改其中的 json 来覆盖文件?

How to overwrite file by changing json in it?

我有一个文件 test.json,其中 json 内容如下 -

{"user_id":3,"created_at":"2020-10-05 04:59:05","expire_user_id":"2,1"}

看完上面json我需要像下面这样重写它。

{"user_id":2,"created_at":"2020-10-05 04:59:05","expire_user_id":"1"}

再举个例子。对于以下 json -

{"user_id":3,"created_at":"2020-10-05 04:59:05","expire_user_id":"1"}

我需要做成这样-

{"user_id":1,"created_at":"2020-10-05 04:59:05"}

下面是我试过的:

$data = json_decode(file_get_contents('test.json'));
if ((int) $data->user_id === $_SESSION['user_id']) {
    // rewrite the file with above logic.
    $content = isset($data->expire_user_id)
               ? json_encode(['user_id' => explode(',', $data->expire_user_id)[0], 'created_at' => (new DateTime('now'))->format('Y-m-d H:i:s')])
               : '';
    file_put_contents('test.json', $content);
}

我尝试了上面的逻辑,我使用 explode 来获取逗号分隔字符串的第一个值,但对如何将剩余的字符串放回 expire_user_id 键感到困惑,或者如果只有其中的一个元素。上面的代码目前无法正常工作,因为混淆了如何将其他东西放回 json.

您可以使用以下函数(您应该将其重命名为更准确的名称)。它的作用是:

  • json_decode JSON,
  • 如果expire_user_id为空,return'{}'(空对象),否则:
    • explode expire_user_id 成数组,
    • 使用 array_shift
    • 删除第一个用户 ID
    • 将其放入 user_id,
    • unsets expire_user_id 如果里面没有更多的值,
    • 使用 implode 用逗号将其连接回来,否则,
  • return重新json_encoded数据。

代码:

/**
 * @throws JsonException
 */
function alterJson(string $json): string
{
    $data = json_decode($json, false, 512, JSON_THROW_ON_ERROR);

    if (empty($data->expire_user_id)) {
        return '{}';
    }

    $data->expire_user_id = explode(',', $data->expire_user_id);
    $data->user_id = array_shift($data->expire_user_id);

    if ($data->expire_user_id) {
        $data->expire_user_id = implode(',', $data->expire_user_id);
    } else {
        unset($data->expire_user_id);
    }

    return json_encode($data, JSON_THROW_ON_ERROR);
}

用法:

$alteredJson = alterJson(<<<JSON
    {"user_id":3,"created_at":"2020-10-05 04:59:05","expire_user_id":"2,1"}
JSON);

Demo