如何将PHP数组2D组合并使用运算符转换为数组1D?

时间:2019-01-12 19:03:57

标签: php arrays

如何在PHP中将2D数组转换为1D数组?请帮助我。.

$array[0]['B0001'] + $array[2]['B0001'] + $array[more]['B0001'];

如果数组键相等(相同),只需将数组的值加(加)并删除重复的数组键...

并像这样转换2D数组:

PHP:5.6.36-示例结果数组2D,var_dump($ array);

之前:

array(2) {
  [0]=>
  array(4) {
    ["B0001"]=>
    string(1) "1"
    ["B0003"]=>
    string(1) "1"
    ["B0004"]=>
    string(1) "1"
    ["B0002"]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    ["B0001"]=>
    string(1) "3"
    ["B0003"]=>
    string(1) "1"
  }
  [more]=>
  array(more) {
    ["B0001"]=>
    string(1) "3"
    ["B0003"]=>
    string(1) "1"
    ["more"]=>
    string(more) "xx"
  }
}

之后:

array(1) {
    ["B0001"]=>
    string(1) "4"
    ["B0003"]=>
    string(1) "2"
    ["B0004"]=>
    string(1) "1"
    ["B0002"]=>
    string(1) "1"
    ["more"]=>
    string(more) "xx"
  }

谢谢!

1 个答案:

答案 0 :(得分:0)

解决了!

$sumArray = array();

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

来源: How to sum all column values in multi-dimensional array?