in_array无法检查php中的数组值 [英] in_array failed to check array value in php
问题描述
我正在建立一个PHP用户权限系统,其中与特定角色相关的所有权限都像数组一样保存在会话中,但是当我尝试检查时,数组中已经存在该值并不正确.
I am making a PHP user permission system where all permission related to specific role are saved in session as like array but when I try to check the it does not true where already the value exists in array.
这是我的会话数组 $ _ SESSION ['userPermissions'] = $ userPermissions;
这是 $ _ SESSION ['userPermissions']
Here is my session array $_SESSION['userPermissions'] = $userPermissions;
here is the var_dump
of $_SESSION['userPermissions']
输出
You are now logged inarray(6) { [0]=> array(1) { ["permission_name"]=> string(11) "create-role" } [1]=> array(1) { ["permission_name"]=> string(11) "update-role" } [2]=> array(1) { ["permission_name"]=> string(11) "delete-role" } [3]=> array(1) { ["permission_name"]=> string(11) "create-user" } [4]=> array(1) { ["permission_name"]=> string(11) "update-user" } [5]=> array(1) { ["permission_name"]=> string(11) "delete-user" } }
我使用波纹管功能检查阵列值
I use bellow function to check array value
// checks if user can delete an user
function canDeleteUser() {
if(in_array('delete-user', $_SESSION['userPermissions'])){
return true;
} else {
return false;
}
}
它总是返回false,请帮助我
it always return false please help me
推荐答案
为使代码正常工作,您需要具有 userPermissions
数组,如下所示:
In order for your code to work you would need to have your userPermissions
array to look as follows:
[
'create-role',
'delete-user',
...the rest...
]
实际上,您的数组如下所示:
while in fact your array look as follows:
[
['permission_name' => 'create-role'],
['permission_name' => 'delete-user'],
...the rest...
]
为了搜索嵌套值,首先提取列:
in order to search for a nested value extract first the column:
if(in_array('delete-user', array_column($_SESSION['userPermissions`], 'permission_name'))){
或按数组搜索:
if(in_array(["permission_name"=>"delete-user"], $_SESSION['userPermissions`]))
但是请注意,第二种方法的安全性要差得多:好像数组将更改(将具有其他元素),这将失败.我强烈建议您使用第一种方法.
yet be aware that the second approach is much less secure: as if the array will change (will have other elements) this will fail. I strongly advise to use the first approach.
这篇关于in_array无法检查php中的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!