简体   繁体   English

PHP检查数组数组是否至少有其中之一具有键的搜索值

[英]PHP check if array of arrays has searching value of key in atleast one of them

I have an array contains data about games per day: 我有一个数组,其中包含每天的游戏数据:

"days" => [
    "2019-07-31" => [
        "3" => [
            'id' => 3,
            'type' => normal,
            'teams' => [
                'teamA', 'teamB',
            ],
            'winnerTeam' => 'teamB',
        ],
        "4" => [
            'id' => 4,
            'type' => ranked,
            'teams' => [
                'teamC', 'teamD',
            ],
            'winnerTeam' => 'teamC',
        ],
    ],
    "2019-07-30" => [
        "1" => [
            'id' => 1,
            'type' => normal,
            'teams' => [
                'teamA', 'teamC',
            ],
            'winnerTeam' => 'teamA',
        ],
        "2" => [
            'id' => 2,
            'type' => normal,
            'teams' => [
                'teamB', 'teamD',
            ],
            'winnerTeam' => 'teamC',
        ],
    ],
];

I would like to get data about all ranked games, but before i would like to check if any ranked game happen during these days. 我想获取有关所有排名游戏的数据,但在此之前,我想检查一下是否有排名游戏发生。 Does someone knows more elegant method than foreach of foreach everything? 有人比说说一切都知道更优雅的方法吗? So my goal is to check before getting data if any game['type'] === 'ranked' 所以我的目标是在获取数据之前检查是否有任何game['type'] === 'ranked'

You can use array-column and array-count-values to achieve that. 您可以使用array-columnarray-count-values来实现。

For each day get all the type using array_column and then count it and return if the type "ranked" is set in the return array. 对于每一天,使用array_column获取所有类型,然后对其计数并返回,如果在返回数组中设置了“ ranked”类型。

Consider the following: 考虑以下:

foreach($arr["days"] as $day => $a) {
    $aaa = array_count_values(array_column($a, "type"));
    if (isset($aaa['ranked'])) 
        echo "Found in $day \n";
}

Live example: 3v4l 直播示例: 3v4l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM