phparraysmultidimensional-arrayrecursiveiterator

php evaluating multidimensional array from inner array to outer araray


How do I solve the following problem using PHP RecursiveIteratorIterator?

$arr = array(
    "sum"=>array(2,4,6, "multiply" => array(1,3,5) ),
    "multiply"=>array(3,3,3, "sum" => array(2,4,6) ),
);

I am expecting the following answers

(2 + 4 + 6 + ( 1 * 3 * 5) ) = 27; 
(3 * 3 * 3 * (2 + 4 + 6)) = 324;

Partial code so far..

   $calc = new ArrayObject($arr);
   $MRI = new RecursiveIteratorIterator(new      MyRecursiveIterator($calc), 1);
   foreach ($MRI as $key=>$value) {
   echo " Current Depth: ". $MRI->getDepth() . "\n"; 
   echo $key . " : " . $value . "\n";
   $currentDepth = $MRI->getDepth();
   for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--)
   { echo "sub Depth: ". $subDepth . "\n"; 
   $subIterator = $MRI->getSubIterator($subDepth);
   // var_dump($subIterator); } }

Solution

  • You can do it like this, do the calculation from the innermost of the array. Check the demo.

    <?php
    function f(&$array)
    {
        foreach($array as $k => &$v)
        {
            if(is_array($v))
            {
                if(count($v) == count($v, 1))
                {
                    unset($array[$k]);
                    if($k == 'sum')
                    {
                        $v =  array_sum($v);
                        $array[] = $v;
    
                    }elseif($k == 'multiply'){
                        $v = array_product($v);
                        $array[] = $v;
                    }else{
    
                        foreach($v as $vv)
                            $array[] = $vv;
                    }
                }else
                    f($v);
            }
        }
    }
    
    while(count($array) != count($array, 1))
    {
        f($array);
    }
    
    print_r($array);
    

    Note:

    traverse array from outer to inner
    traverse array from inner to outer