首页 > 解决方案 > 更新json替换php中表单中的变量输入

问题描述

问候,我是 PHP 新手,目前正在寻找一种编辑 json 的方法。我有一个表格来输入要编辑的键。我从表单回显输入并成功显示输出,但它没有传递给 json 文件进行更新。代码如下。

function testfun()
{
    // read file
    $data = file_get_contents('Book2.json');

    // decode json to array
    $json_arr = json_decode($data, true);

    foreach ($json_arr as $key => $value) {
        if ($value['CELL_NAME'] == $_POST['in_cell']) {
            $json_arr[$key]['@25'] = $_POST['in_remark'];
        }
    }

    // encode array to json and save to file

    file_put_contents('Book2.json', json_encode($json_arr));
}
//you this post contain test?
//test is the the button when i submit the form

if (array_key_exists('test',$_POST))
{
    testfun();
}

我错过了什么吗?

标签: phpjson

解决方案


试试我的代码。

 function testfun()
{
// read file
$data = file_get_contents('Book2.json');

// decode json to array
$json_arr = array(json_decode($data, true));
foreach ($json_arr as $key => $value) {
    if ($value['CELL_NAME'] == $_POST['in_cell']) {
    $json_arr[$key]['@25'] = $_POST['in_remark'];
    }
}

// encode array to json and save to file

file_put_contents('Book2.json', json_encode($json_arr));
}


if (array_key_exists('test',$_POST))
{
    testfun();
}

推荐阅读