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

PHP统计国家对应项目数量报错且重复显示国家ID修复求助

问题原因

  • Undefined offset报错:首次对$country_counts[$country_id]执行自增操作时,对应数组键尚未初始化,PHP会抛出下标未定义的通知。
  • 国家ID重复展示:判断逻辑存在错误,原有条件会让已统计过的国家ID也进入展示分支,且你将表格行输出逻辑直接写在项目遍历循环中,每匹配到对应国家的项目就会输出一次行,自然会出现重复。

修正方案

建议先独立统计每个国家对应的项目总数,再遍历统计结果输出表格内容,既可以避免下标报错,也能保证每个国家仅展示一次。

修正后完整代码

<table>
    <tr>
        <th>Country ID</th>
        <th>Country Name</th>
        <th>Number of Place</th>
    </tr>
    <?php 
    $country_counts = [];
    // 第一步:先统计所有国家的项目数量
    foreach( $projects as $project ) {
        $country_id = $project['Project']['country_id'];
        // 初始化未存在的国家计数
        if (!isset($country_counts[$country_id])) {
            $country_counts[$country_id] = 0;
        }
        $country_counts[$country_id]++;
    }
    // 第二步:遍历统计结果输出表格,每个国家仅输出一行
    foreach ($country_counts as $country_id => $count) {
    ?>
    <tr>
        <td style="width: 30%"><?php echo $country_id; ?></td>
        <td style="width: 30%"><?php echo 'Country Name'; ?></td>
        <td style="width: 30%"><?php echo $count; ?></td>
    </tr>
    <?php 
    }
    $proects_num = count($projects); 
    ?>
</table>
<?php 
    echo '<br>' .'Total projects numbers are: ' . $proects_num .'<br>'; 
    echo $html->link('Home ', $this->webroot.'countries/index/');
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:06:05