简体   繁体   English

如果子数组不是相同的长度(不同的键数),php和多个子数组的值

[英]php sum values of multiple subarrays if subarrays are not the same length (not the same number of keys)

Have such array (placed code here http://codepad.viper-7.com/mTqf6W ) 有这样的阵列(在这里放置代码http://codepad.viper-7.com/mTqf6W

Array
(
[17,bank stmt,1,23,3,2014] => Array
    (
        [0] => Array
            (
                [RecordDay] => 17
                [Amount] => 1.5
            )
    )
[17,invoice,2,17,3,2014] => Array
    (
        [0] => Array
            (
                [RecordDay] => 17
                [Amount] => 0.21
            )

        [1] => Array
            (
                [RecordDay] => 17
                [Amount] => 1
            )

    )


)

Want to get totals of [Amount] for each subarray. 想要获得每个子阵列的[Amount]总数。 For the first subarray there is only one key, so Total equals to [Amount] . 对于第一个子阵列,只有一个键,因此Total等于[Amount] But for the second subarray there are 2 keys (may be more than 2 keys), so in some way need to sum all [Amount] 但是对于第二个子阵列有2个键(可能超过2个键),所以在某种程度上需要总和[Amount]

For [17,bank stmt,1,23,3,2014] would be 1.5, [17,invoice,2,17,3,2014] would be 1.21 对于[17,bank stmt,1,23,3,2014]将是1.5, [17,invoice,2,17,3,2014]将是1.21

Following some examples PHP Array_Sum on multi dimensional array trying to create code. 下面的一些例子PHP Array_Sum在多维数组上尝试创建代码。 Created 创建

$values = array('Amount' => 0);
$counter = 0;
foreach ($temp_array as $key => $item) {
$values['Amount'] += $item[$counter]['Amount'];
$counter++;
}

Get error 'Notice: Undefined offset: 2' 获取错误'注意:未定义的偏移量:2'

If you have PHP 5.5+, this can be done with array_column() and array_sum() : 如果你有PHP 5.5+,可以使用array_column()array_sum()来完成:

foreach ($array as $sub) {
    echo array_sum(array_column($sub, 'Amount'));
}

Use array_map() to extract all the amounts and then array_sum() to sum the values in the array: 使用array_map()提取所有数量,然后使用array_sum()对数组中的值求和:

foreach ($array as $sub) {
    echo array_sum(array_map(function($item) {
        return $item['Amount'];
    }, $sub));
}

Output: 输出:

1.5
1.21

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM