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

PHP中如何统计二维数组列数?求customerId数组元素计数方法

在PHP中统计customerId数组的元素数量

嘿,我来帮你搞定这个需求!根据你的场景,我分两种常见情况给你解决方案:

情况1:统计所有评论中customerId数组的总元素个数

如果每个$val里的customerId是一个数组(比如单条评论关联多个用户ID),想要算出所有评论里的customerId总数,可以用这两种方法:

方法一:用数组函数链式处理(简洁高效)

// 从$result数组中提取所有customerId子数组
$customerIdLists = array_column($ratings['result'], 'customerId');
// 给每个子数组统计长度后求和
$totalCustomerIds = array_sum(array_map('count', $customerIdLists));
echo $totalCustomerIds;

方法二:循环累加(直观易懂)

$total = 0;
foreach ($ratings['result'] as $val) {
    // 先确保customerId是数组且不为空,避免报错
    if (isset($val['customerId']) && is_array($val['customerId'])) {
        $total += count($val['customerId']);
    }
}
echo $total;

情况2:统计包含有效customerId的评论条数

如果你的需求是统计有多少条评论存在customerId(不管是单个值还是非空数组),可以用array_filter来过滤:

$validCount = count(array_filter($ratings['result'], function($val) {
    // 判断customerId存在且有效:非空值 或者 是有元素的数组
    return isset($val['customerId']) && 
           (!empty($val['customerId']) || (is_array($val['customerId']) && count($val['customerId']) > 0));
}));
echo $validCount;

小建议

为了让Blade模板更简洁,建议你在控制器里先计算好这些统计值,再传递到模板中使用,比如:

// 控制器代码
$ratings = // 从API获取数据
$commentCount = count($ratings['result']);
$totalCustomerIds = array_sum(array_map('count', array_column($ratings['result'], 'customerId')));

return view('your-view', compact('ratings', 'commentCount', 'totalCustomerIds'));

然后在模板里直接用{{ $totalCustomerIds }}输出就好啦!

内容的提问来源于stack exchange,提问作者Kevin The Pleb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:27:59