获取我的对象数组的总和

时间:2017-02-03 10:59:11

标签: php arrays multidimensional-array

我有对象数组:

[Income] => Array
    (
        [0] => Array
            (
                [Today] => Array
                    (
                        [0] => Array
                            (
                                [Sum] => Array
                                    (
                                        [Total] => 61.9700
                                    )
                            )

                        [1] => Array
                            (
                                [Sum] => Array
                                    (
                                        [Total] => 60.2300
                                    )
                            )
                    )
            )

        [1] => Array
            (
                [Today] => Array
                    (
                        [0] => Array
                            (
                                [Sum] => Array
                                    (
                                        [Total] => 51.9500
                                    )
                            )

                        [1] => Array
                            (
                                [Sum] => Array
                                    (
                                        [Total] => 53.6900
                                    )
                            )
                    )
            )
    )

如何为每个级别正确加总Total

Income->[0]->Today should be 122.20
Income->[1]->Today should be 105.64

我试过这个: 编辑:

for($i=0;$i<count($item->Today);$i++){
    $total = 0;
    foreach ($item->Today as $amount) {
        if(is_object($amount[$i]->Sum->Total)){ 
        echo $amount[$i]->Sum->Total;
        $total += $amount[$i]->Sum->Total;
        }
    }
    if($i==0){
        echo '<td>'.$total.'</td>';     
    }   
}   

我收到此错误警告:main():无法添加元素今天数字3时只存在0个这样的元素。..用我现在使用的代码更新了我的帖子

我把它作为XML的对象而不是数组
我知道出了什么问题!我仍然在努力学习多维数组:(

2 个答案:

答案 0 :(得分:1)

你需要foreach:

$array=array();
foreach($arr['Income'] as $key=>$val){
    $array['Income'][$key]['Today']=0;
    foreach($val['Today'] as $k=>$v){
        foreach($v as $keys=>$values){
            $array['Income'][$key]['Today']=$array['Income'][$key]['Today']+$values['Total'];
        }
    }
}

print_r($array);//your output.

DEMO

答案 1 :(得分:1)

<?php
$income;
for($i = 0; $i < count($income["Income"]); $i++) {
    $total = 0;
    foreach ($income["Income"][$i]["Today"] as $amount) {
        $total += $amount["sum"]["Total"];
    }
    $income["Income"][$i]["Today"] = $total;
}

只需输入数据数组$income=//your data

即可