[英]PHP check if string is in array
I have an array that looks like this: 我有一个看起来像这样的数组:
{"permissions":["1","2"]}
I'm trying to check if a given string is in the permissions array with the following function 我正在尝试使用以下功能检查给定字符串是否在权限数组中
function hasPermission($permission) {
return in_array($permission, array_column($this->permissions, 'permissions'));
}
When calling the function giving it the string "1" it return false even though 1 is in the permissions array 当调用给它字符串“ 1”的函数时,即使权限数组中为1,它也会返回false
Any help would be appreciated 任何帮助,将不胜感激
Thanks 谢谢
EDIT 编辑
Here is a var Dump of the converted array 这是转换后的数组的var Dump
array(1) {
["permissions"]=>
array(2) {[0]=> string(1) "1"
[1]=> string(1) "2"
}
}
Try like this... 这样尝试...
<?php
$json = '{"permissions":["1","2"]}';
$arr = json_decode($json,true);
print_r($arr);
echo in_array(1,$arr['permissions']); // returns 1 if exists
?>
So your function must be like this.... 所以你的功能一定是这样的...
function hasPermission($permission) {
return in_array($permission, $this->permissions['permissions']);
}
array_column
doesn't support 1D arrays, it returns an empty array if so. array_column
不支持一维数组,如果支持则返回一个空数组。
Your $permissions array is 1D, so just use $this->permissions['permission']
to access it. 您的$ permissions数组是1D,因此只需使用
$this->permissions['permission']
即可访问它。
return in_array($permission, $this->permissions['permissions']);
Example: 例:
$array = ['permissions' => ['1', '2']];
echo (int)in_array('1', array_column($array, 'permissions')); // 0
echo (int)in_array('1', $array['permissions']); // 1
Try this this will work. 试试这个,这将起作用。
$permission = json_decode('{"permissions":["1","2"]}',true);
echo "<pre>";print_r($permission);
if(is_array($permission)){
echo "this is an array";
}else{
echo "Not an array";
}
Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.