简体   繁体   English

如何使用php获取多维数组特定索引中的值的总和?

[英]How to get sum of values in specific index of multidimensional array using php?

I have this this array in my code我的代码中有这个数组

Array
(
    [1] => Array
        (
            [1] => 4
            [5] => 7
        )

    [2] => Array
        (
            [1] => 2
            [5] => 5
        )

    [3] => Array
        (
            [1] => 2
            [5] => 5
        )

    [4] => Array
        (
            [1] => 6
            [5] => 9
        )

    [5] => Array
        (
            [1] => 6
            [5] => 8
        )

)
1

How could I get sum element with same index?如何获得具有相同索引的 sum 元素? Forexample - sum of all element with index 5 or index 1. If it possible without hardcode.例如 - 索引为 5 或索引为 1 的所有元素的总和。如果没有硬编码可能的话。

You can use this code您可以使用此代码

This is demo code for test这是用于测试的演示代码

$items = array(
 array(1 => 1, 2 => 'White Shirt', 3 => 2),
 array(1 => 2, 2 => 'Blue Shirt', 3 => 3)
);
echo "<pre>";
print_r($items);

echo array_sum(array_column($items, 3)); // output 5

it will work for php 5.5+
 // PHP 5.5+
 echo array_sum(array_column($array, 'yourindexname')); // 

// PHP 4+
function sumArray($item) {
return $item['yourindex'];
}

echo array_sum(array_map('sumArray', $array));

/ PHP 5.3+
echo array_sum(array_map(
function($item) {
    return $item['yourindex'];
}, $items)
);



$sumvalue = array();

foreach ($array as $k=>$sub_array) {
  foreach ($sub_array as $id=>$value) {
  $sumvalue [$id]+=$value;
}
}

 print_r($sumvalue );

You could do the following:您可以执行以下操作:

function getSumOfId($array, $id) {
   $sumOfId = 0;

   foreach($array as $arr) {
      $sumOfId += $arr[$id];
   }
   return $sumOfId;
}

This way you'll loop through all your arrays, and get the complete sum of a specific ID.通过这种方式,您将遍历所有数组,并获得特定 ID 的完整总和。

You can use it like this getSumOfId($yourArray, 5)你可以像这样使用它getSumOfId($yourArray, 5)

You can use array_reduce() to sum target values.您可以使用array_reduce()对目标值求和。

$sum = array_reduce($arr, function($carry, $item){
    $carry += $item[5];
    return $carry;
});
echo $sum;

Check code result in demo演示中检查代码结果

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

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