I'm trying to add new "commands" to an existing json file and I'm stuck, I have a .json file with subarrays.
This is how the file looks like:
{
"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"
}
}
I want to add new values into "template_commands" Here is the php code:
<?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';
}
}
?>
It almost works but it puts the newly added in like this:
"0":{
"Test":[
"Lets see if this works!",
"1"
]
}
What am I doing wrong? I tried it with array_push() as well and it didn't work either.