首页 > 解决方案 > in_array() 如何检查两个值 PHP WordPress

问题描述

我正在检查用户的两个角色,但它不起作用。我正在检查它,in_array()但是当我只传递一个值时它正在工作,但是当我传递两个值时它不起作用。

PHP具有两个用户角色值,它不起作用。代码有什么问题?

$user = wp_get_current_user();
if ( in_array( 'editor','author', (array) $user->roles ) ) {
        remove_menu_page('edit.php');
    }
}

标签: phpwordpress

解决方案


使用 array_intersect() 函数使用大海捞针的目标,并确保交集精确地等于目标:

$user = wp_get_current_user();
$haystack = (array) $user->roles;

$target = array('editor', 'author');

if(count(array_intersect($haystack, $target)) == count($target)){
    // all of $target is in $haystack
}

推荐阅读