php - 如何修改此 PHP 代码以将数据发送到服务器上的 json 文件,如下所示 json 格式
问题描述
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
{
if(empty($_POST["title"]))
{
$error = "<label class='text-danger'>Enter details</label>";
}
else if(empty($_POST["image"]))
{
$error = "<label class='text-danger'>Enter Written By</label>";
}
else
{
if(file_exists('myfile.json'))
{
$current_data = file_get_contents('myfile.json');
$array_data = json_decode($current_data, true);
$extra = array(
'title' => $_POST['title'],
'image' => $_POST["image"],
'link' => $_POST['link'],
'info' => $_POST['info'],
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('myfile.json', $final_data))
{
$message = "<label class='text-success'>Added Successfully</p>";
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
以上是我用于将数据发送到服务器上存在的 json 的 PHP 代码。
{
"Apple": [
{
"title": "iphone5",
"image": "lllllll",
"link": "llllll",
"info":"llllll"
},
{
"title": "iphone6",
"image": "lllllll",
"link": "llllll",
"info":"llllll"
}
]
}
以上是我在使用 PHP 提交数据后想要拥有的 json 文件格式,它不应该覆盖 myfile 或类似的东西,我希望它使用 PHP 在数组中添加更多的孩子
[
{
"title": "Aiphone5",
"image": "lllllll",
"link": "llllll",
"info":"llllll"
},
{
"title": "Aiphone6",
"image": "lllllll",
"link": "llllll",
"info":"llllll"
}
]
如果我如上所示运行php代码,则json的o / p如上
解决方案
我找到了这个答案
用这个
$array_data['Apple'][] = $extra;
代替
$array_data[] = $extra;
推荐阅读
- reactjs - React:在渲染之前生成对象数组以避免更改不受控制的输入错误
- reactjs - React js更改字段指定属性名称
- extjs - 如何默认展开 Rowwidget
- performance - 类型不稳定性会严重影响性能怎么办?
- php - 使用 ODBC 和 PHP 的 SQL Server INSERT 查询:奇怪的语法错误
- wordpress - 如何在 Woocommerce 中更改 myadress.php
- sitecore - 以编程方式编辑 sitecore 项目的字段而不更新它的“更新”字段
- r - 根据条件求和或代入
- html - 如何在CSS中向右定位并使项目低于一个和另一个
- java - Java-Paradox 驱动程序 - 可以选择但不能修改