【问题标题】:Why removing item from array of roles breaks when storing the array as a JSON?为什么在将数组存储为 JSON 时从角色数组中删除项目会中断?
【发布时间】:2019-09-10 10:12:01
【问题描述】:

我有一个 Symfony 4 项目,其中包含一个带有“角色”数组的用户实体(在我的数据库中的 JSON 中)。

/**
 * @ORM\Column(type="json")
 */
private $roles = [];

/**
 * @see UserInterface
 */
public function getRoles(): array
{
    $roles = $this->roles;
    // guarantee every user at least has ROLE_USER
    $roles[] = 'ROLE_USER';

    return array_unique($roles);
}

public function addRole($role)
{
    if (!in_array($role, $this->roles)) {
        array_push($this->roles, $role);
    }

    return $this;
}

public function hasRole($role)
{
    if (in_array($role, $this->roles)) {
        return true;
    }

    return false;
}

public function removeRole($role)
{
    if ($this->hasRole($role)) {
        unset($this->roles[array_search($role, $this->roles)]);
    }

    return $this;
}

所以,我的User 角色可能类似于:

["ROLE_VALIDATEUR", "ROLE_SUPER_VALIDATEUR"]

但是,当我使用删除函数删除角色时,例如“ROLE_SUPER_VALIDATEUR”(因此,在那之后,我只有“ROLE_VALIDATEUR”角色),我的角色数组有时会像这样中断:

{"1" : "ROLE_VALIDATEUR"}

我的删除功能有什么问题?

【问题讨论】:

    标签: php arrays json symfony


    【解决方案1】:

    添加这个:

    $this->roles = array_values($this->roles);
    

    在您的 removeRole($role) 方法中紧随其后:

    unset($this->roles[array_search($role, $this->roles)]);
    

    问题是unset() 删除了数组值,但它没有重新索引数组。所以剩下一个没有0索引的数组(在你的例子中),只有一个1索引。

    当转换为 JSON 时,它被解释为一个关联数组,而不是一个普通的索引数组。

    通过使用array_values(),您正在重建包含用户实体角色的索引数组,并且该属性将正确保存在数据库中。

    【讨论】:

      猜你喜欢
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 2017-12-21
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多