【问题标题】:PHP array_push adds unnecessary quotesPHP array_push 添加不必要的引号
【发布时间】:2019-01-05 23:20:18
【问题描述】:

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

预期的 JSON

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

相反,我得到:

"users": [
        {
          "username": "admin",
          "password": "admin",
          "isAdmin": true
        },
        {
          "username": "bleh",
          "password": "meh",
          "isAdmin": false
        },
 "{\"isAdmin\":false,\"username\":\"test1\",\"password\":\"$2y$10$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;

我知道使用文件而不是数据库并不是“最佳实践”,但现在使用文件就足以满足我的需求,因此请不要评论“使用 db 代替”之类的内容。

【问题讨论】:

    标签: php json array-push


    【解决方案1】:

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

    您可以删除此行:

    $newUserJson = json_encode($this);

    然后更新这一行

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

    这应该可以解决问题

    【讨论】:

      【解决方案2】:

      替换:

      $newUserJson = json_encode($this);
      

      下面一行:

      $newUserJson = $this;
      

      【讨论】:

        猜你喜欢
        • 2018-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-23
        • 2020-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多