我正在尝试创建一个json_encode
函数,它输出一个PHP数组,如下所示:
{"userA":{"user":"userA","admin":true,"user_id":"000"}}
遗憾的是,我只是使用PHP类得到了以下输出:
{"user":"d4ne","admin":"true","user_id":"000"}
我的PHP类:
<?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;
}
}
?>
有人知道我为什么不让它工作吗?
编辑:
如果我编辑类以将代码推入数组,如:
<?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;
}
}
?>
然后输出将如下所示:
{"swagg_ma_blue":{"user":"swagg_ma_blue","admin":true,"user_id":"000"},"0":{"d4ne":{"user":"d4ne","admin":"true","user_id":"000"}}}
其中包含"0":
,不应该存在,有人知道吗?
在add_mod()函数中尝试以下代码
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;
}
在上面的代码中,我添加了$this->username以获得一个额外的数组,您需要在数组中添加额外的"userA"。结果如下。
{"userA":{"user":"userA","admin":true,"user_id":"000"}}
这对你来说合适吗:
返回json_encode(数组($this->username=>$ds));
我真的不明白你的意思。如果你的意思是数组中的数组,你可以试试这个。
$data = array( 'userA'=> array(
'user' => $this->username,
'admin' => $this->status,
'user_id' => $this->user_id
));
//{"userA":{"user":"userA","admin":true,"user_id":"000"}}