php - 使用 PHP 将数据附加到 JSON 文件的顶部
问题描述
我正在使用 PHP 表单将数据附加到 JSON 文件,但现在它将新数据添加到 JSON 文件的底部
我想将新数据添加到 JSON 文件的顶部而不是底部。
这是我用来将数据附加到 JSON 的我的 PHP 代码。
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error = "<label class='text-danger'>Enter Name</label>";
}
else if(empty($_POST["author"]))
{
$error = "<label class='text-danger'>Enter Author</label>";
}
else if(empty($_POST["category"]))
{
$error = "<label class='text-danger'>Enter Thumbnail</label>";
}
else if(empty($_POST["url"]))
{
$error = "<label class='text-danger'>Enter URL</label>";
}
else
{
if(file_exists('wallpaper.json'))
{
$current_data = file_get_contents('wallpaper.json');
$array_data = json_decode($current_data, true);
$extra = array(
'name' => $_POST['name'],
'author' => $_POST["author"],
'category' => $_POST["category"],
'url' => $_POST["url"]
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('wallpaper.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
这是 wallpaper.JSON 目前它添加这样的数据 -
[
{
"name": "Old Code",
"author": "Old Code",
"category": "Old Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
},
{
"name": "New Code",
"author": "New Code",
"category": "New Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
}
]
我想要这样-
[
{
"name": "New Code",
"author": "New Code",
"category": "New Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
},
{
"name": "Old Code",
"author": "Old Code",
"category": "Old Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
}
]
解决方案
那么你可以在你的用例中使用 use array_reverse 但我会做另一种方法
$array_data[] = $extra;
$array_data = array_reverse($array_data);
$final_data = json_encode($array_data);
但更好的方法是使用 array_unshift
array_unshift($array_data, $extra);
来源:https ://www.php.net/manual/en/function.array-unshift.php
推荐阅读
- java - Dagger - 以最少的仪式注册没有@Inject 的课程
- grafana - 在 Grafana 的 Promql 查询中引用选择的时间范围(从、到)
- bash - 在 100+MB SQL 转储中插入三个块(SQL 行)
- extjs - ExtJS:如何使 tabreorderer 插件选项卡定位有状态
- c - STM32 CAN 通信 Rx 期间接收随机数据字节
- apache - 无法解决 htaccess 重写问题(对 seo 友好的 URL)
- ios - 如何确保字典中的所有键都已初始化
- haskell - 结合来自两个 Either Monad 的结果
- reactjs - 当我使用 Metro bundle 运行和测试应用程序时,它运行良好。但是当我构建 android apk 它无法正常工作时,它会再次重新启动
- django - FilterView、get_context_data() 不起作用。没有属性“object_list”,但有一个