php 检查关联数组键是否存在于另一个数组中

6vl6ewon  于 2023-01-29  发布在  PHP
关注(0)|答案(2)|浏览(141)

我有两个关联数组,如果第一个数组的键出现在第二个数组中,我将尝试查找它们。

<?php
    $team_member = ["Person_1" => 0, "Person_2" => 0, "Person_3" => 0, "Person_4" => 0];
    $today_active_member = ["Person_1" => 0, "Person_3" => 0, "Person_4" => 0];

    $i = count($team_member);

    while($i--){ //4, 3, 2, 1, false
        if(in_array(key($team_member), $today_active_member)) { // check is key available in second array?
            echo key($team_member) . " is present today.<br/>";
            next($team_member); // goes to the next key
            // code goes here
        } else {
            echo key($team_member) . " isn't present today.<br/>";
            next($team_member); // goes to the next key
        }
    }

但是上面的代码没有给出正确的输出。现在的输出是:
Person_1今天出席。
人员_2今天出席。
人员_3今天出席。
人员_4今天出席。
它应输出:
Person_1今天出席。
Person_2今天没有出席。
人员_3今天出席。
人员_4今天出席。
我怎么才能找到第一个数组的键,而第二个数组的键呢?我也试过用array_keys()array_search()来解决这个问题,但是没有用

5sxhfpxr

5sxhfpxr1#

相反,您应该使用array_key_exists()函数,该函数有两个参数:要检查的键和要签入的数组。

<?php
$team_member = ["Person_1" => 0, "Person_2" => 0, "Person_3" => 0, "Person_4" => 0];
$today_active_member = ["Person_1" => 0, "Person_3" => 0, "Person_4" => 0];

$i = count($team_member);

while($i--){ 
    if(in_array(key($team_member), array_keys($today_active_member))) { 
        echo key($team_member) . " is present today.<br/>";
        next($team_member); 
    } else {
        echo key($team_member) . " isn't present today.<br/>";
        next($team_member); 
    }
}

PHP在线版:https://onlinephp.io/c/48b7c

rm5edbpk

rm5edbpk2#

使用foreach looparray_key_exists()有一种简单得多的方法

$team_member = ["Person_1" => 0, "Person_2" => 0, "Person_3" => 0, "Person_4" => 0];
$today_active_member = ["Person_1" => 0, "Person_3" => 0, "Person_4" => 0];

foreach( $team_member as $key=>$val){
    if (array_key_exists($key, $today_active_member)){
        echo $key . " is present today.<br/>";
    } else {
        echo $key . " isn't present today.<br/>";
    }
}

结果

Person_1 is present today.<br/>
Person_2 isn't present today.<br/>
Person_3 is present today.<br/>
Person_4 is present today.<br/>

相关问题