php - 使用子数组写入 Jsonfile
问题描述
我正在尝试将新的“命令”添加到现有的 json 文件中,但我被卡住了,我有一个.json
带有子数组的文件。
这是文件的样子:
{
"template_commands":{
"web":[
"Webadded cmds are working!",
"Rights['0']"
],
"streamer":[
"This is only for Streamers!",
"Rights['3']"
],
"admin":[
"This is only for Admins!",
"Rights['2']"
],
"mod":[
"This is only for mods",
"Rights['1']"
],
"taka":[
"taka",
"Rights['2']"
]
},
"doggo_counter":0,
"admins":{
"touru":"name",
"juufa":"name"
}
}
我想在“template_commands”中添加新值这是 php 代码:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function get_data() {
$name = $_POST['name'];
$file_name='commands'. '.json';
if(file_exists("$file_name")) {
$current_data=file_get_contents("$file_name");
$array_data=json_decode($current_data, true);
$extra=array(
$_POST['name'] => array($_POST['branch'],$_POST['year'])
);
$array_data['template_commands'][]=$extra;
echo "file exist<br/>";
return json_encode($array_data);
}
else {
$datae=array();
$datae[]=array(
'Name' => $_POST['name'],
'Branch' => $_POST['branch'],
'Year' => $_POST['year'],
);
echo "file not exist<br/>";
return json_encode($datae);
}
}
$file_name='commands'. '.json';
if(file_put_contents("$file_name", get_data())) {
echo 'success';
}
else {
echo 'There is some error';
}
}
?>
它几乎可以工作,但它将新添加的内容如下:
"0":{
"Test":[
"Lets see if this works!",
"1"
]
}
我究竟做错了什么?我也试过了,array_push()
也没有用。
解决方案
您的问题的根源是您添加元素的方式:
$array_data['template_commands'][]=$extra;
通过使用[]
您指示 PHP 添加一个新条目,同时自动确定键(这将是0
,因为您的数组是关联的,而不是数字的)。所以你在做什么可以显示为试图添加
[
'Test' => [
"Lets see if this works!",
"1"
]
]
在下一个可用的数字索引处,在这种情况下为零。
这种添加方式适用于数值数组,但不适用于关联数组。对于他们,您应该明确定义索引。所以你真正想要的是添加
[
"Lets see if this works!",
"1"
]
键下Test
。为此,请将您的代码更改为:
// only the inner array of what you used
$extra = array($_POST['branch'], $_POST['year']);
// the index is directly specified during assignment
$array_data['template_commands'][$_POST['name']] = $extra;
推荐阅读
- sql - 在 Access 和 SQL Server 之间加入 DateTime 有时会失败
- c++ - 在子类函数覆盖中省略具有默认值的参数
- angular - 在一个组件中运行多个组件
- php - Ubuntu 18.04下php7.1-zip安装
- c# - 数据库更改对 Xtrareports 的影响
- jss - 如何使用 JSS 设置滚动条样式?
- python-3.x - 如何从不同的文件打印函数内的变量?
- c# - C# 使用 LINQ 过滤对象列表中具有最大值的每个对象
- python - 安装 GNURadio 时出现 PyGTK 问题
- angularjs - AngularJS - 选中新复选框时取消选中以前的复选框