简体   繁体   中英

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'

You can use array-column and array-count-values to achieve that.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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