user3201132
user3201132

Reputation:

PHP Programming: Sum of nth level multi-dimensional array

I am stuck, and unable to code the sum of a multi-dimensional array with different types: below is an example instance.

$multi_dimes_array = array(
    "1"=>array
    (1,2,5,6,7),
    "2"=> "Apple",
    "3"=> array("1"=>array('some_more',
                'banana',
                'ship',array(1,5,6,7,array(4,4,4,4))))
);

My code looks like:

foreach ($multi_dimes_array as $val) {           
  if(is_array($val))
  {
    $total = $total + $val;
  }
}

but I get an error.

Upvotes: 1

Views: 275

Answers (2)

Elentriel
Elentriel

Reputation: 1237

The way i see it, you require a recursive function or a whole lot of fors,ifs and whiles. So recursive it is.

function array_sums($arraypart)
{
  if(!is_array($arraypart))
  {
   return intval($arraypart);
  }
  else
  {
      $sub_sum = 0;
      foreach($arraypart as $new_part)
      {
          $sub_sum += array_sums($new_part);
      }
      return $sub_sum;
  }
}

Something along these lines perhaps? It goes like this: if it is not an array, try to get its integer (or float) value and return it. (i saw you had some string too, that could be dangerous if not parsed, actually how do you plan to add the strings?)

if it is an array, foreach of its elements, call the function again, sum their returns, and return them yourself.

Upvotes: 0

Olipro
Olipro

Reputation: 3529

You should implement a recursive function:

function deep_array_sum($arr) {
    $ret = 0;
    foreach($arr as $val) {
        if (is_array($val))
            $ret += deep_array_sum($val);
        else if(is_numeric($val))
            $ret += $val;
    }
    return $ret;
}

Upvotes: 1

Related Questions