如何在php中从数组求和中排除元素?

时间:2011-10-31 16:23:48

标签: php arrays sum

我有这个数组:

[Jessica CS] => Array
    (
        [2011-04-20] => Array
            (
                [0] => 69.90
                [cancel] => 1311145200
                [1] => 29.95
                [2] => 69.90
            )
    )

[Rex CS] => Array
    (
        [2011-04-20] => Array
            (
                [0] => 119.94
                [cancel] => 
            )

        [2011-04-26] => Array
            (
                [0] => 199.50
                [cancel] => 
                [1] => 29.95
            )
....

我正在使用循环将这些值加在一起:

$i=0;
foreach($dates as $d){
$total[$i] += array_sum($value[$d]);
#i++;
}

这会将所有内容添加到一起,我想要的是排除[cancel]字段被添加到array_sum

编辑:我可能会添加int的值,但不确定如何对它们进行排序

任何想法?

感谢

2 个答案:

答案 0 :(得分:1)

就个人而言,我会更改数组的布局,使其更像:

[Jessica CS] => Array
    (
        [2011-04-20] => Array
            (
                [cancel] => 1311145200
                [costs] => Array
                    (
                        [0] => 69.90
                        [1] => 29.95
                        [2] => 69.90
                    )
                )
    )

用最相关的名称替换[费用]。

使用现有阵列
失败

$i=0;
foreach($dates as $d){
    $total[$i] += array_sum(array_diff_key($value[$d], array('cancel'));
    #i++;
}

答案 1 :(得分:0)

只需循环遍历数组,也许就像这样:

$input = array(
    'Jessica CS' => array(
        '2011-04-20' => array(
            0 => 69.9,
            'cancel' => 1311145200,
            1 => 29.95,
            2 => 69.90,
        ),
    ),
    'Rex CS' => array(
        '2011-04-20' => array(
            0 => 119.94,
            'cancel' => null,
        ),
        '2011-04-26' => array(
            0 => 199.50,
            'cancel' => null,
            1 => 29.95,
        )
    )
);

$totals = array();

foreach($input as $person => $dates){
    $totals[$person] = 0;
    foreach ($dates as $date => $values) {
        foreach ($values as $key => $val) {
            if ($key !== 'cancel') {
                $totals[$person] += $val;
            }
        }
    }
}

print_r($totals)

产地:

Array
(
    [Jessica CS] => 169.75
    [Rex CS] => 349.39
)