I'm trying to add a array to a json file using php.
How I want it to look (formatting does not matter):
{
// Already stored in json file
"swagg_ma_blue":{
"user":"swagg_ma_blue",
"admin":true,
"user_id":"000"
},
// Should be added using php
"dnl":{
"user":"dnl",
"admin":"true",
"user_id":"000"
}
}
How my outcome actually looks like:
{"swagg_ma_blue":{"user":"swagg_ma_blue","admin":true,"user_id":"000"},"0":{"user":"d4ne","admin":true,"user_id":"000"}}
As you see the array index/key of the second element is called "0" but I need it to have the user value.
My code:
<?php
class add_mod_class {
function __construct($username, $status){
$this->username = $username;
$this->status = $status;
$this->user_id = '000';
$this->json_file = 'includes/json/mods.json';
}
function get_json(){
$json_content = file_get_contents($this->json_file);
$json = json_decode($json_content, true);
return $json;
}
function mod_handler(){
if($this->status == 'admin'){
return true;
}else{
return false;
}
}
function add_mod(){
$mods = $this->get_json();
$data = array(
'user' => $this->username,
'admin' => $this->mod_handler(),
'user_id' => $this->user_id
);
array_push($mods, $data);
$new_json_string = json_encode($mods);
return $new_json_string;
}
}
?>
First idea was to use was:
$data[$this->username] = array(
'user' => $this->username,
'admin' => $this->mod_handler(),
'user_id' => $this->user_id
);
But this would still return "0": in it. I Would appreciate every kind of help.
array_push()of course. How / where are you calling this method and using the results?array_push()sadly to re-create thejson_encode. After this would be done I would save the json code to a file using:file_put_contents()and im calling the method in the following format:if(!empty($_POST)){ require_once('includes/add_mod_class.php'); $mod_user = $_POST['user']; $mod_status = $_POST['status']; $mod_add = new add_mod_class($mod_user, $mod_status); $object = $mod_add->add_mod(); }array_pushadd an element at the end of your array, with a numeric index. Just use$modes[$this->username] = $datainstead ofarray_push($mods, $data)