php - 如何在 AuthComponent::user() 中搜索数组?

标签 php arrays cakephp authorization has-and-belongs-to-many

我一直在 CakePHP 2.6 中开发一个应用程序,其中一名工作人员最初只属于一个部门,但系统要求现在发生了变化,并且工作人员和部门之间存在 HasAndBelongsToMany (HABTM) 关系。

现在证明这是一个问题,我只向 View 中属于某个部门的员工显示信息,因为我的 AuthComponent::user() 对象现在包含一个部门数组。

有没有一种简单的方法可以循环遍历 AuthComponent::user() Department 数组并检查值是否与所选值匹配?

HABTM 关系之前的旧 View 代码:

if (AuthComponent::user('admin') == 1 || (AuthComponent::user('department_id') == $department['Department']['id'])) {
    // Some code here
};

AuthComponent::user() 数组:

array(16) {
  ["id"]=>
  string(1) "6"
  ["salutation"]=>
  string(2) "Mr"
  ["firstname"]=>
  string(6) "Joe"
  ["lastname"]=>
  string(4) "Bloggs"
  ["email"]=>
  string(21) "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2989d97dc909e9d959581b2979f939b9edc919d9f" rel="noreferrer noopener nofollow">[email protected]</a>"
  ["role"]=>
  string(23) "Teacher"
  ["admin"]=>
  bool(true)
  ["dos"]=>
  bool(false)
  ["school_id"]=>
  string(1) "1"
  ["active"]=>
  bool(true)
  ["School"]=>
  array(2) {
    ["id"]=>
    string(1) "1"
    ["name"]=>
    string(10) "School Name"
  }
  ["Department"]=>
  array(3) {
    [0]=>
    array(2) {
      ["id"]=>
      string(1) "4"
      ["name"]=>
      string(20) "Careers & University"
    }
    [1]=>
    array(2) {
      ["id"]=>
      string(2) "14"
      ["name"]=>
      string(9) "Geography"
    }
    [2]=>
    array(2) {
      ["id"]=>
      string(2) "16"
      ["name"]=>
      string(3) "ICT"
    }
  }
}

最佳答案

可能最简单的方法是使用 CakePHP's Hash::extract()方法构建属于用户的所有部门的简单数组,然后检查该部门是否存在于该数组中,如下所示:-

$user = AuthComponent::user();
$departments = Hash::extract($user, 'Department.{n}.id');
if (
    (int)$user['admin'] === 1
    || in_array($department['Department']['id'], $departments) === true
) {
    // Some code here
}

CakePHP 中的哈希实用程序非常值得一看,因为它提供了一些非常方便的数组操作方法,可以处理 find() 查询返回的数组。

关于php - 如何在 AuthComponent::user() 中搜索数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33807185/

相关文章:

php - 在 Symfony Controller 中访问容器

php - MySQL 和 PHP 的日期范围

C++:如何让动态数组的索引由文件中的行确定

cakephp - 如何让关联模型运行 __construct?

php - 组合或继承

PHP Beanstalk 的 laravel 权限在存储/框架/缓存上被拒绝

php - 如何使用 bindModel 和自定义查找器将 CakePHP 2 模型关联更改为深度链接?

cakephp - 在 cakePHP 中限制和重定向其他用户

C-排序大型2D整数数组的最快方法

javascript - 如何检查数组中是否存在某个值并获取下一个值?