I'm trying to create a json_encode
function which outputs a PHP array like this:
{"userA":{"user":"userA","admin":true,"user_id":"000"}}
Sadly I just get the following output using my PHP class:
{"user":"d4ne","admin":"true","user_id":"000"}
My PHP class:
<?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 add_mod(){
$mods = $this->get_json();
array_push($mods, $data);
$ds = array(
'user' => $this->username,
'admin' => $this->status,
'user_id' => $this->user_id
);
$new_json_string = json_encode($ds);
return $new_json_string;
}
}
?>
Does anyone have a idea why I wouldn't get it working?
EDIT:
If i edit the class to push the code into the array like:
<?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 add_mod(){
$mods = $this->get_json();
$data[$this->username] = array(
'user' => $this->username,
'admin' => $this->status,
'user_id' => $this->user_id
);
array_push($mods, $data);
$new_json_string = json_encode($mods);
return $new_json_string;
}
}
?>
Then the output would look like the following:
{"swagg_ma_blue":{"user":"swagg_ma_blue","admin":true,"user_id":"000"},"0":{"d4ne":{"user":"d4ne","admin":"true","user_id":"000"}}}
Which contains "0":
, which shoudlnt be there, anyone a idea?
Try the following code in add_mod() function
function add_mod(){
$mods = $this->get_json();
array_push($mods, $data);
$ds[$this->username] = array( //added $this->username
'user' => $this->username,
'admin' => $this->status,
'user_id' => $this->user_id
);
$new_json_string = json_encode($ds);
return $new_json_string;
}
In the above code I added $this->username to have a extra array that you want extra "userA" in the array. and will result as the following.
{"userA":{"user":"userA","admin":true,"user_id":"000"}}
Is this ok for you:
return json_encode(array($this->username => $ds));
I don't really understand what do you mean. If you mean array in array you can try this.
$data = array( 'userA'=> array(
'user' => $this->username,
'admin' => $this->status,
'user_id' => $this->user_id
));
//{"userA":{"user":"userA","admin":true,"user_id":"000"}}