<?php
$r1=array("n"=>3,"ni"=>2,["nis"=>3,[["nish"=>4],[["nishi"=>"n"],[["nishi"=>true]]]]]);
echo "<pre>";
//print_r($r1);
echo "</pre>";
$sum=0;
for ($i=0;$i<count($r1);$i++) {
$curr=$r1[$i];
if (is_array($curr)) {
$sum += array_sum($curr);
} else if (is_numeric($curr)) {
$sum += $curr;
}
echo $sum;
}
?>
我试图找到数组中值的总和并保留字符串。如果有人知道答案请帮助
答案 0 :(得分:1)
使用array_walk_recursive
遍历数组的每个元素:
$sum = 0;
array_walk_recursive($r1, function($v) use (&$sum) {
if (is_numeric($v)) $sum += $v;
});
var_dump($sum); # 12
修改:不使用array_walk_recursive
功能使用
function array_walk_recursive_rewrite(array $data) {
$sum = 0;
foreach ($data as $v) {
if (is_array($v)) {
$sum += array_walk_recursive_rewrite($v);
} elseif (is_integer($v)) {
$sum += $v;
}
}
return $sum;
}
var_dump( array_walk_recursive_rewrite($r1) ); # 12