0

I have a mulit demensional array like this ...

enter image description here

** note the array has closing brackets which is not shown in this image. so theres no issue in the syntax.

I want to add the values in each key (Openness, Conscientiousness) together so that i have a array like :

      Array{
              [Openness]=> Array(
                    [0] => 16
             )
              [Conscientiousness]=>Array (
                     [0]=> 10
              )
         }

When i tried this code after looking through existing questions :

      $sumArray = array();

    foreach ($finalarr as $k=>$subArray) {
      foreach ($subArray as $id=>$value) {
        //$sumArray[$id]+=$value;
        array_key_exists( $id, $sumArray ) ? $sumArray[$id] += $value :      $sumArray[$id] = $value;
            }
        }

   print_r($sumArray);

I get :

enter image description here

which is not what i want. ANy ideas how to fix the array?

2
  • Take a look at array_sum() Commented Nov 8, 2016 at 2:56
  • The keys of $sumArray should be $k, not $id. Commented Nov 8, 2016 at 2:59

2 Answers 2

0

You can do it with array_sum() and one loop:

$sumArray = array();
foreach ($finalarr as $k => $subArray) {
    $sumArray[$k] = array_sum($subArray);
}

If you really need the elements of $sumArray to be arrays rather than just the sums, it becomes:

$sumArray = array();
foreach ($finalarr as $k => $subArray) {
    $sumArray[$k] = array(array_sum($subArray));
}

But I'm not sure why you would want that.

Sign up to request clarification or add additional context in comments.

2 Comments

I get a error saying array_sum expects parameter 1 to be array when i run the first bit of your coding. anyways i have posted my solution taking into accout all the comments.
I don't see how yours can work when mine doesn't. You're calling array_sum() with the same value.
0

Okay as suggested in the comments i used the array_sum and it worked. I changed the foreach to :

**removed the inner loop which was unnecessary

    foreach ($finalarr as $k=>$subArray) {

        $finalarr[$k]=array_sum($subArray);

}

and it gave me the output :

     Array{
          [Openness]=> 16
          [Conscientiousness]=> 10

     }

Thanks for the comments !!

7 Comments

What's the point of the inner loop? You never use $id or $value. You're just doing the same sum of $subArray repeatedly.
Where are those parentheses in the output coming from? You have ) with no matching (.
I removed the inner loop and got the same result so your right that second loop is not needed ! thanks.
So what's the difference from my answer?
i dont know. when i run your code i get the error i mentioned
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.