2

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.

1 Answer 1

4

The source of your problem is the way you're adding your element:

$array_data['template_commands'][]=$extra;

By using [] you're instructing PHP to add a new entry while automatically determining the key (which will be 0, since your array is associative, not numerical). So what you're doing can be shown as trying to add

[
    'Test' => [
        "Lets see if this works!",
        "1"
    ]
]

at the next available numerical index, in this case zero.

This way of adding is suitable for numeric arrays, but not for associative ones. For them, you should explicitly define the index. So what you really want is to add

[
    "Lets see if this works!",
    "1"
]

under the key Test. To achieve that, change your code to this:

// 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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the explaination! I knew it was something to do with the way I send the values to the file but since my knowlege of .json is very slim I couldn't figure it out, I got close to it after a lot of google research but I didn't get it to work. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.