PHP array_push 添加不必要的引号

PHP array_push adds unnecessary quotes

所以我需要按原样将数据添加到我的 JSON。

expected JSON

  "users": [
    {
      "username": "admin",
      "password": "admin",
      "isAdmin": true
    },
    {
      "username": "bleh",
      "password": "meh",
      "isAdmin": false
    }
  ]

instead I get:

"users": [
        {
          "username": "admin",
          "password": "admin",
          "isAdmin": true
        },
        {
          "username": "bleh",
          "password": "meh",
          "isAdmin": false
        },
 "{\"isAdmin\":false,\"username\":\"test1\",\"password\":\"y$fSb.0bw\\/MbtBx.PHerRdU.gahYnRezZZuy8VYL41ah8YwPxW6hOTq\"}"
          ]

我对这个问题失去了理智,因为我找不到找到我的代码的哪一部分将额外的引号和反斜杠添加到添加的字符串的方法。

这是我的 php 代码,负责将值添加到 JSON:

      if (self::checkExistence($this->username) == true){
        return false;
    }

    $newUserJson = json_encode($this);

    $inp = file_get_contents(getcwd() . self::USERS_LOCATION);
    $tempArray = json_decode($inp,true);

    array_push($tempArray["users"], $newUserJson);

    $jsonData = json_encode($tempArray);
    file_put_contents(getcwd() . self::USERS_LOCATION, $jsonData);

    return true;

我知道使用文件代替数据库不是"best practice",但现在使用文件足以满足我的需求,所以请不要评论[=26] =].

这是因为您对字符串进行了双重编码。您对它进行一次编码 $newUserJson,然后将其插入数组 $tempArray["users"] 并对该数组进行编码。

您可以删除此行:

$newUserJson = json_encode($this);

然后更新这一行

array_push($tempArray["users"], $this);

这应该可以解决问题

替换:

$newUserJson = json_encode($this);

使用以下行:

$newUserJson = $this;