带有键/索引规范的PHP数组到json

时间:2016-04-13 13:49:05

标签: php json

我试图使用php将数组添加到json文件中。

我希望它看起来(格式无关紧要):

{
    // 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"
    }
}

我的结果实际上是这样的:

{"swagg_ma_blue":{"user":"swagg_ma_blue","admin":true,"user_id":"000"},"0":{"user":"d4ne","admin":true,"user_id":"000"}}

如您所见,第二个元素的数组索引/键被称为"0",但我需要它具有user值。

我的代码:

<?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;
        }
    }
?>

第一个想法是使用is:

$data[$this->username] = array(
    'user' => $this->username,
    'admin' => $this->mod_handler(),
    'user_id' => $this->user_id
);

但是这仍然会返回"0":。我会感激各种帮助。

1 个答案:

答案 0 :(得分:1)

您的第一种方法很好,除非您应该分配到$mods数组而不是$data。这是更正后的功能:

function add_mod(){
    $mods = $this->get_json();

    $mods[$this->username] = array(
        'user' => $this->username,
        'admin' => $this->mod_handler(),
        'user_id' => $this->user_id
    );

    $new_json_string = json_encode($mods);
    return $new_json_string;
}