使用count($ array)只检索匹配的$ key

时间:2019-04-08 05:21:07

标签: php arrays wordpress function loops

我正在运行$array的循环,其中仅包含具有匹配用户角色(来自Wordpress用户)的结果。

我有循环:

// custom function that returns the user's role (administrator, reader, etc)
$userRole = get_current_user_role();

foreach( $location_array as $key => $location ) {
    if( in_array( $userRole, $location['c'] ) ) {
        // do the things

        echo '<div style="width: calc( 100vw / ' . count($array) . ');">';
            echo $location['a'];
        echo '</div>';

    }
}

$array组成:

Array (
    [1] => Array (
        [a] => Location 1
        [b] => loc04
        [c] => Array ( [administrator] => administrator )
    )
    [2] => Array (
        [a] => Location 2
        [b] => loc23
        [c] => Array ( [administrator] => administrator, [publisher] => publisher )
    )

    [3] => Array (
        [a] => Location 3
        [b] => loc12
        [c] => Array ( [publisher] => publisher, [viewer] => viewer )
    )
) 

但是,当我尝试获取$array的数量时,它将返回所有$key的数量,并且我不知道如何将其范围缩小到{ {1}}

我尝试将循环中的in_array( $userRole, $location['c']放入变量中,然后输出该变量,但是除了返回值1之外,我没有成功,但是管理员有两个匹配项

1 个答案:

答案 0 :(得分:0)

您不能连续使用数组上的计数。您需要先过滤

您可以将array-filter用作:

$arr = [["b" => "loc04", "c" => ["administrator" => "administrator"]]];
$arr[] = ["b" => "loc23", "c" => ["administrator" => "administrator", "publisher" => "publisher"]];
$arr[] = ["b" => "loc12", "c" => ["publisher" => "publisher", "viewer" => "viewer"]];
$role = "administrator";
$a = array_filter($arr, function ($e) use ($role) {return in_array($role, $e["c"]);});

现在$a将包含2个元素。

如果键与值相同,则最好使用isset(更快-O(1)代替O(n)),作为:

$a = array_filter($arr, function ($e) use ($role) {return isset($e["c"][$role]);});

然后,您可以遍历$a并执行以下操作:

foreach($a as $location) {
    echo '<div style="width: calc( 100vw / ' . count($a) . ');">';
    echo $location['a'];
    echo '</div>';
}

实时示例:3v4l