我正在尝试检查元素是否不在数组中而不是要重定向页面: 我的代码如下:
$id = $access_data['Privilege']['id'];
if(!in_array($id,$user_access_arr))
{
$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
}
我很困惑如何检查元素是否不在数组中。
因为我们可以使用php的in_array
函数检查元素是否存在于数组中。
我正在尝试使用(!in_array)
检查它,但我没有得到结果。
请帮忙。
答案 0 :(得分:38)
简单地
$os = array("Mac", "NT", "Irix", "Linux");
if (!in_array("BB", $os)) {
echo "BB is not found";
}
答案 1 :(得分:5)
if (in_array($id,$user_access_arr)==0)
{
$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
}
答案 2 :(得分:4)
尝试使用array_intersect方法
$id = $access_data['Privilege']['id'];
if(count(array_intersect($id,$user_access_arr)) == 0){
$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
}
答案 3 :(得分:2)
我认为你需要的一切都是 array_key_exists :
if (!array_key_exists('id', $access_data['Privilege'])) {
$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
}
答案 4 :(得分:2)
$id = $access_data['Privilege']['id'];
if(!in_array($id,$user_access_arr));
$user_access_arr[] = $id;
$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
答案 5 :(得分:1)
$array1 = "Orange";
$array2 = array("Apple","Grapes","Orange","Pineapple");
if(in_array($array1,$array2)){
echo $array1.' exists in array2';
}else{
echo $array1.'does not exists in array2';
}
答案 6 :(得分:1)
你可以使用内置函数的php in_array()来检查
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>
您也可以使用此
进行检查<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
如果你只是检查in_array()就好了,但如果你需要检查一个值是否存在并返回相关的键,则array_search是一个更好的选择。
$data = array(
0 => 'Key1',
1 => 'Key2'
);
$key = array_search('Key2', $data);
if ($key) {
echo 'Key is ' . $key;
} else {
echo 'Key not found';
}
答案 7 :(得分:1)
我更喜欢这个
if(in_array($id,$user_access_arr) == false)
各自
if (in_array(search_value, array) == false)
// value is not in array
答案 8 :(得分:0)
$data = array(
0 => 'Key1',
1 => 'Key2'
);
$key = array_search('Key2', $data);
if ($key) {
echo 'Key is ' . $key;
} else {
echo 'Key not found';
}