我有json文件,它具有以下json对象结构
{
"Project_3": {
"link": "",
"title": "",
"desc": ""
},
"Project_2": {
"link": "",
"title": "",
"desc": ""
},
"Project_1": {
"link": "",
"title": "",
"desc": ""
}
}
现在我想要的是像这样更新这个json文件
Project_3 = Project_2
Project_2 = Project_1
我的意思是Projects_3的内容应该与Projects_2的内容一样,Project_2的内容应该与Project_1的内容一样,Project_1的内容应该是表单数据的下一个输入
Uptil现在这是我在php中尝试过的。
$projects = json_decode(file_get_contents('../json/recent_projects.json','w'));
$projects->Project_3 = $projects->Project_2;
$projects->Project_2 = $projects->Project_1;
$projects->Project_1->link = htmlspecialchars($_POST['project_link']);
$projects->Project_1->title = htmlspecialchars($_POST['project_name']);
$projects->Project_1->desc = htmlspecialchars($_POST['project_desc']);
$fh = fopen("../json/recent_projects.json", 'w') or die('File cannot be opened');
fwrite($fh, json_encode($projects,JSON_UNESCAPED_UNICODE));
fclose($fh);
但是,Project_3和Project_2的内容始终保持不变,只有Project_1更新。我不明白为什么会发生这种情况。
修改
我得到了我的问题的答案,但为什么在这个过程中没有使用。我没有得到!热烈欢迎任何帮助或建议!
答案 0 :(得分:1)
测试了您的代码,但Project_3和Project_2确实发生了变化。我得到的错误是Project_2和Project_1都被$_POST
变量更新了。所以我只是unset()
Project_1。现在它的工作就像你想要的那样。
<?php
$json = '{
"Project_3": {
"link": "L3",
"title": "T3",
"desc": "D3"
},
"Project_2": {
"link": "L2",
"title": "T2",
"desc": "D2"
},
"Project_1": {
"link": "L1",
"title": "T1",
"desc": "D1"
}
}';
$projects = json_decode($json);
echo "<pre>";
print_r($projects);
$projects->Project_3 = $projects->Project_2;
$projects->Project_2 = $projects->Project_1;
unset($projects->Project_1);
$projects->Project_1->link = htmlspecialchars($_POST['project_link']);
$projects->Project_1->title = htmlspecialchars($_POST['project_name']);
$projects->Project_1->desc = htmlspecialchars($_POST['project_desc']);
echo "<pre>";
print_r($projects);
$fh = fopen("../json/recent_projects.json", 'w') or die('File cannot be opened');
fwrite($fh, json_encode($projects,JSON_UNESCAPED_UNICODE));
fclose($fh);
?>
输出:
stdClass Object
(
[Project_3] => stdClass Object
(
[link] => L3
[title] => T3
[desc] => D3
)
[Project_2] => stdClass Object
(
[link] => L2
[title] => T2
[desc] => D2
)
[Project_1] => stdClass Object
(
[link] => L1
[title] => T1
[desc] => D1
)
)
stdClass Object
(
[Project_3] => stdClass Object
(
[link] => L2
[title] => T2
[desc] => D2
)
[Project_2] => stdClass Object
(
[link] => L1
[title] => T1
[desc] => D1
)
[Project_1] => stdClass Object
(
[link] => L5
[title] => T5
[desc] => D5
)
)