我对PHP编程真的很陌生,我正在尝试使用PHP到.json文件实现以下结构;
{
"1": {
"number": "4",
"color": "black"
},
"2": {
"number": "0",
"color": "green"
}
}
我想做的是,当我使用"add.php"文件将数据发布到这里时。它将更新 .json 文件,如下所示;
{
"1": {
"number": "4",
"color": "black"
},
"2": {
"number": "0",
"color": "green"
},
"3": {
"number": "12",
"color": "red"
}
}
"数字"和"颜色"将来自我从索引中发布的帖子.php带有jQuery;
$('#add_outcome').on('submit',function (e) {
e.preventDefault();
$.ajax({
url: 'add.php',
cache: false,
type: 'POST',
data : {
"number" : $('#add_outcome select').val(),
"color" : $('#add_outcome #color_info').val()
},
success: function(json) {
console.log("Done, data sent"); }
});
});
是否可以用PHP更新这种结构?如果无法计算下一个"ID",在我的示例中是 1、2、3 等(通过提交增加),我可以从索引 PHP 发布数据。
现在对我来说最重要的是熟悉如何使用PHP更新这种结构。
JSON数据将来自文件,它的路径是"json/outcome.json"。
将此代码添加到add.php
文件中
<?php
$json_array = json_decode(file_get_contents('json/outcome.json'), true);
$json_array[] = array('number' => $_POST['number'], 'color' => $_POST['color']);
file_put_contents('json/outcome.json', json_encode($json_array));
?>
试试这段代码
<?php
$file = json_decode(file_get_contents('path/to.json'), true);
//do whatever you want as $file is now an array
$file[] = array('number' => 12, 'color' => 'red');
file_put_contents('path/to.json', json_encode($file));