【问题标题】:Checking in_array from db with codeigniter使用 codeigniter 从 db 检查 in_array
【发布时间】:2017-09-11 18:33:01
【问题描述】:

如何使用下面的 sn-ps 实现检查角色?我想要实现的是能够根据分配的角色对用户进行身份验证。 in_array() 不适用于返回的数组。

返回的数组是:

array (size=2) 0 => object(stdClass)[40] public 'role' => string '2' (length=1) 1 => object(stdClass)[41] public 'role' => string '5' (length=1)

数据:

DB TABLE
id user_id role
1  4       2
2  4       5

型号

//get logged user roles
public function user_roles($id){
    $userDB  = $this->quickDB();
    $userdata = $userDB->query("SELECT role
                            FROM role_assignment
                            WHERE user_id = $id
                            ")->result();
    $userDB->close();
    return ($userdata);
}

控制器:

public function user_roles()
{
    $roles=$this->Master_model->user_roles('4');

    if (in_array("1", $roles)) 
    {
        echo "Admin<br>";
    }
    if (in_array("2", $roles)) 
    {
        echo "Teacher<br>";
    }
    if (in_array("5", $roles)) 
    {
        echo "Academic<br>";
    }
}

【问题讨论】:

  • 您的问题是什么?你有什么问题?

标签: php mysql codeigniter codeigniter-3


【解决方案1】:

您的代码中的in_array 不起作用。您需要进行两项更改。

首先 - 将您的数据库输出更改为数组,现在您将获得对象:

$userdata = $userDB->query("SELECT role
                        FROM role_assignment
                        WHERE user_id = $id
                        ")->result_array();

第二 - 遍历数据库结果并返回修改后的数组:

$user_roles = array();
foreach ($userdata as $val) {
    $user_roles[] = $val['role'];
}
return $user_roles;

这两项更改都在模型的 user_roles 函数中。

【讨论】:

  • 谢谢;但是在哪里放置第二个代码?如果它返回 $user_roles,foreach 的用途是什么?
  • 但是我把 $value['role'] 改成了 $val['role']
猜你喜欢
  • 2018-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
相关资源
最近更新 更多