-1

How to convert the 2D arrays to 1D array in PHP? Help me Please..

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

if the array key is equal (same), just addition (plus) the value of array and remove duplicate array key...

and convert 2D array like this :

PHP: 5.6.36 - Example Result array 2D, var_dump($array);

before :

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"
  }
}

after :

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

Thank You!!

Irwan Kusuma
  • 41
  • 1
  • 1
  • 3

1 Answers1

0

solved!

$sumArray = array();

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

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

Irwan Kusuma
  • 41
  • 1
  • 1
  • 3