如果存在匹配项,则跳过(子)数组的值

时间:2019-05-10 19:05:14

标签: php arrays

我既有一个数组(团队)又有一个子数组(团队成员)。我想回显所有比赛的列表,但我想检查团队成员,如果有则不回声。

in_array()是正确的功能吗?

array
 -- Team 1
    --- Anne
    --- Julia
    --- Jack
 -- Team 2
    --- Tom
    --- Lisa
    --- James
 -- Team 3
    --- James
    --- Julia
    --- Donald 

检查Jack是否应该“回声”

array
 -- Team 2
    --- Tom
    --- Lisa
    --- James
 -- Team 3
    --- James
    --- Julia
    --- Donald 

检查詹姆斯应该“回声”

array
 -- Team 1
    --- Anne
    --- Julia
    --- Jack

如果James存在,我当前的代码回显如下。

array
 -- Team 1
    --- Anne
    --- Julia
    --- Jack
 -- Team 2
    --- Tom
    --- Lisa   
 -- Team 3
    --- Julia
    --- Donald 

但是如果发现有团队成员匹配,我想跳过整个团队,而不仅仅是一个成员。

2 个答案:

答案 0 :(得分:2)

您可以使用df.groupby('Player').filter(lambda d: '2018-2019' in d.Year.values)

m = df.Year.values == '2018-2019'
i, u = pd.factorize(df.Player)
a = np.zeros(len(u), bool)
np.logical_or.at(a, i, m)

df[a[i]]

        Year Player   TM  GP
0  2018-2019    Joe  MTL  78
1  2017-2018    Joe  MTL  82
2  2016-2017    Joe  MTL  80
5  2018-2019   Jack  MIN  82

搜索foreachLive Demo

搜索$arr = [ 'Team 1' => [ 'Anne','Julia','Jack' ], 'Team 2' => [ 'Tom','Lisa','James' ], 'Team 3' => [ 'James','Julia','Donald' ] ]; $res = []; foreach($arr as $key => $val){ if(!in_array('James',$val)){ $res[$key] = $val; } } Live Demo

答案 1 :(得分:2)

使用foreach循环,您可以循环浏览multi-dimensional array个团队,然后在每个子in_array上使用array来检查团队中是否存在该名称。使用<pre>print_r,您可以漂亮地打印出不包含要搜索名称的团队。

**我的答案使用与@Rakesh相同的逻辑(他的用法很好,简单且有效),但是我可能会使用命名约定等对我的逻辑进行更多的解释。

<?php

function checkForTeamMember($memberName, $teams) {
    echo "Looking for teams without: ".$memberName ."<pre>";       
    $teamsToPrint = [];
    foreach($teams as $teamKey => $memberArray) {
        if(!in_array($memberName, $memberArray)) {
             $teamsToPrint[$teamKey] = $memberArray;
        }
    }
    print_r($teamsToPrint);
    echo "</pre>";
}

$teamGroups = [];
$teamGroups['Team 1'] = array('Anne', 'Julia', 'Jack');
$teamGroups['Team 2'] = array('Tom', 'Lisa', 'James');
$teamGroups['Team 3'] = array('James', 'Julia', 'Donald');

checkForTeamMember('James', $teamGroups);
checkForTeamMember('Jack', $teamGroups);
?>

实时示例:https://3v4l.org/DsQc2