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

PHP:如何对含stdClass对象的数组的credit字段求和?

解决方案

1. 对'credit'字段求和

这里提供两种实用的求和方式:

方法一:循环遍历累加

// 假设你的目标数组是$creditObjects
$totalCredit = 0;
foreach ($creditObjects as $obj) {
    // 先判断对象是否存在credit属性,避免报错
    if (property_exists($obj, 'credit')) {
        $totalCredit += $obj->credit;
    }
}

// 输出求和结果
echo $totalCredit; // 最终结果:2350000

方法二:使用array_reduce函数简化代码

$totalCredit = array_reduce($creditObjects, function($carry, $obj) {
    return $carry + (property_exists($obj, 'credit') ? $obj->credit : 0);
}, 0);

echo $totalCredit; // 最终结果:2350000

2. 生成指定的HTML有序列表

直接遍历数组拼接HTML代码即可实现需求:

$html = '<ol>';
foreach ($creditObjects as $obj) {
    if (property_exists($obj, 'credit')) {
        $html .= '<li>' . intval($obj->credit) . '</li>';
    }
}
$html .= '</ol>';

// 输出生成的HTML
echo $html;

运行后会输出你需要的结果:

<ol><li>650000</li><li>500000</li><li>500000</li><li>500000</li><li>200000</li></ol>

额外提示

  • 加入property_exists判断是为了避免数组中存在不含credit属性的对象时触发错误
  • 使用intval可以确保输出内容为整数格式,避免字符串等异常值干扰显示

内容的提问来源于stack exchange,提问作者Jije's Stackoverflow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:25:19