You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何统计JSON中含game字段的在游戏用户数量?

Counting Users Currently in a Game

Hey there! Your current code counts all members in the list, but we need to tweak it to only count those who have the game field present (since that's your indicator for being in a game). Here are two straightforward ways to do this in PHP:

Method 1: Using a Foreach Loop (Easy to Read)

Initialize a counter, loop through each member, and increment the counter only if the game field exists:

$count = 0;
foreach ($result['members'] as $member) {
    // Check if the 'game' key exists in the member array
    if (array_key_exists('game', $member)) {
        $count++;
    }
}

Then output it just like you were before:

<strong><?php echo $count; ?></strong>

Method 2: Using array_filter (Concise)

PHP's array_filter function lets you filter the members array to only include those with the game field, then count the filtered results:

// Filter members to only those with a 'game' field
$playingMembers = array_filter($result['members'], function($member) {
    return array_key_exists('game', $member);
});

// Count the filtered array
$count = count($playingMembers);

Quick Note: isset() vs array_key_exists()

If you're sure the game field will never be null when present, you could use isset($member['game']) instead of array_key_exists(). However, array_key_exists() is more reliable here—it will return true as long as the game key exists, even if its value is null (which matches your original logic of "game field exists = user is in game").

For your sample JSON snippet:

"members": [ { "username": "Squadman", "game": { "name": "World of Warcraft" }, } ]

Both methods will return a count of 1, which is correct since only Squadman is in a game.

内容的提问来源于stack exchange,提问作者user7186420

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:30:14