简体   繁体   English

如何检查数组的数组在PHP或Laravel中其值中是否具有键值对

[英]How to check whether an array of array have a key value pair in its values in PHP or Laravel

I have the following array. 我有以下数组。 I want to know whether any of the values of the array contains the key-value pair "RoleCode" => "Admin" . 我想知道数组的任何值是否包含键值对"RoleCode" => "Admin"

[
  0 => [
    "RoleCode" => "Admin"
    "RoleName" => "Administrator"
  ]
  1 => [
    "RoleCode" => "PM"
    "RoleName" => "ProjectManager"
  ]
  2 => [
    "RoleCode" => "ScheduleUser"
    "RoleName" => "Schedule User"
  ]
]

I can write a long code to find it out like the following: 我可以编写一个长代码来查找它,如下所示:

$isAdmin = false;
foreach ($user['Roles'] as $role) {
    if ($role['RoleCode'] == 'Admin') {
        $isAdmin = true;
    }
}

Is there any way to do this in a better way? 有什么办法可以更好地做到这一点?

You could use array_column() and in_array() : 您可以使用array_column()in_array()

$isAdmin = in_array('Admin', array_column($user['Roles'], 'RoleCode')) ;
  • array_column() will return an array with all values from 'RoleCode' key array_column()将返回具有'RoleCode'键的所有值的数组
  • in_array() will check if Admin is inside in_array()将检查Admin是否在内部

It depends what is better way. 这取决于哪种更好的方法。

Current solution with adding break when item found: 找到项目时添加break当前解决方案:

$isAdmin = false;
foreach ($user['Roles'] as $role) {
    if ($role['RoleCode'] == 'Admin') {
        $isAdmin = true;
        break;
    }
}

will be O(n) in worst case. 在最坏的情况下将为O(n)

Other solutions, like one in another answer 其他解决方案,如另一个答案

$isAdmin = in_array('Admin', array_column($user['Roles'], 'RoleCode'));

This will be O(n) + O(1) in best case and O(n) + O(n) in worst. 这将是O(n) + O(1)在最好的情况下和O(n) + O(n)在最差。 More than initial foreach . 不仅仅是最初的foreach

Another one is filtering: 另一个是过滤:

$isAdmin = !empty(array_filter(
    $user['Roles'], 
    function ($v) { return $v['RoleCode'] == 'Admin'; }
));

It is always O(n) 总是O(n)

So, from the point of readability and performance, initial code is the winner. 因此,从可读性和性能的角度来看,初始代码是赢家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM