如何使用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); } }
答案 0 :(得分:1)
你可以这样做,从数组的最里面做计算。查看 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);
注意:强>
traverse array from outer to inner
traverse array from inner to outer
答案 1 :(得分:0)
简单易行的解决方案: -
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script type="text/javascript">
var cordenax = -25.363;
var cordenay = 131.044;
</script>
<script src="js.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCd71PV2l5xNnRiVat4sKNV56CJcBhyS5E&callback=initMap">
</script>
</body>
希望它有所帮助!