0

I have read a lot of answers here on SO but havent been able to sort this out.

I have multidimensional array that looks like this:

Array

(
[0] => Array
    (
        [0] => 
        [1] => 655
    )

[1] => Array
    (
        [0] => IT-82
        [1] => 14
    )

[2] => Array
    (
        [0] => IT-21
        [1] => 5
    )

[3] => Array
    (
        [0] => IT-82
        [1] => 7
    )

[4] => Array
    (
        [0] => 
        [1] => 3
    )

[5] => Array
    (
        [0] => IT-21
        [1] => 4
    )

[6] => Array
    (
        [0] => 
        [1] => 3
    )

[7] => Array
    (
        [0] => IT-21
        [1] => 3
    )

[8] => Array
    (
        [0] => IT-72
        [1] => 7
    )

[9] => Array
    (
        [0] => IT-75
        [1] => 22
    )

[10] => Array
    (
        [0] => IT-75
        [1] => 3
    )
)

I would like to sum the values according to the keys ending with a single array like:

Array 
(
      => 661
IT-82 => 21
IT-21 => 12
IT-82 => 12
IT-72 => 7
IT-75 => 25
)

Tried with

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

but this only returned the sum of all the values.

Any help appreciated.

  • 1
    All members of an array must have a key. In your desired result, there is no key for value `661`. Such an array does not exist. What would you like to use as a key when your sub-array has nothing at index 0? – BeetleJuice Jul 26 '16 at 13:17
  • The array actually does output like i pasted. The mysql filed from which is generated is empty. Applying any variable which I would set a string would be great combined to @JayeshChitroda answer which works perfectly –  Jul 26 '16 at 13:59

2 Answers2

0

Try:

$sumArray = array();
foreach ($array as $k=>$subArray) { //loop through array
  if(isset($sumArray[$subArray[0]]))
    $sumArray[$subArray[0]] += $subArray[1]; // set 0th index as key and 1st as value and add value to current index
  else 
    $sumArray[$subArray[0]] = $subArray[1];
}
print_r($sumArray);

Output:

Array
(
    [] => 661
    [IT-82] => 21
    [IT-21] => 12
    [IT-72] => 7
    [IT-75] => 25
)
Jayesh Chitroda
  • 4,987
  • 13
  • 18
-1

I suppose it should be:

foreach ($array as $subArray) {
    $sumArray[$subArray[0]] += $subArray[1];
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • This is really elegant; much cleaner than what I was doing. I wold add `if !isset then set` logic before accessing the array because this code will generate many many `undefined index` warnings on a large array. – BeetleJuice Jul 26 '16 at 13:31
  • This approach seems faster and neater but actually gives wrong results. They are far higher then the right ones as if they get summed too many times –  Jul 26 '16 at 13:40