php 从内部数组到外部数组评估多维数组

php evaluating multidimensional array from inner array to outer araray

如何使用 PHP RecursiveIteratorIterator 解决以下问题?

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

我期待以下答案

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

到目前为止的部分代码..

   $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); } }

你可以这样做,从数组的最里面开始计算。检查 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);

注:


简单易行的解决方案:-

$arr = array("sum"=>array(2,4,6, "multiply" => array(1,3,5) ),"multiply"=>array(3,3,3, "sum" => array(2,4,6)));
    foreach($arr as $key => $newarr){
        if($key =="sum"){
            $sum = array_sum($newarr);
            $product = array_product($newarr['multiply']);
            $finalarray[$key] = $sum+$product;
        }elseif($key =="multiply") {
            $product = array_product($newarr);
            $sum = array_sum($newarr['sum']);
            $finalarray[$key] = $sum*$product;
        }
    }
    echo "<pre>"; print_r($finalarray);

希望对您有所帮助!