PHP评估从内部数组到外部araray的多维数组 [英] php evaluating multidimensional array from inner array to outer araray

查看:74
本文介绍了PHP评估从内部数组到外部araray的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我期望以下答案

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


推荐答案

您可以这样做,从数组的最内部进行计算。检查 演示

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

注意:

从外到内的遍历数组

从内到外的遍历数组

这篇关于PHP评估从内部数组到外部araray的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆