1

如何使用 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); } }
4

2 回答 2

1
于 2017-12-06T04:35:35.747 回答
0

简单易行的解决方案:-

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

希望能帮助到你!

于 2017-12-06T04:45:55.853 回答