【发布时间】:2018-03-25 20:24:49
【问题描述】:
我不明白为什么我在 PHP 中的简单 FOR 循环无法正确计算嵌套数组值(整数)的总和。
任何人都可以帮助我理解这一点吗?
沙盒: http://sandbox.onlinephpfunctions.com/code/6ec5385e297b8e1d24727305c8e644370e38b00b
<?php
//This function returns a random Array (one Array with two nested Arrays with random values):
function ArrCreate() {
$n = 2; //Two nested Arrays declaration.
$newArray = [];
for ($i = 0; $i < $n; $i++) {
$newArray[$i] = [];
for ($j = 0; $j < $n; $j++) {
$newArray[$i][$j] = mt_rand(1, 2); //Random values declaration.
}
}
return $newArray;
}
//This function returns SUM of an Array values (simple FOR loop is used):
function ArrSum($array) {
$sum = 0;
for ($i = 0; $i < count($array); $i++) {
for ($j = 0; $j < count($array[$i]); $j++) {
$sum += $array[$i][$j];
}
}
return $sum;
}
//Let's print the random Array using ArrCreate function:
echo '<pre>';
print_r(ArrCreate());
echo '</pre>';
//Let's declare the random Array using $arr variable:
$arr = ArrCreate();
//Let's calculate SUM of declared Array values using ArrSum function:
echo "Sum of an array values: " .ArrSum($arr); //WRONG SUM RESULT :(
【问题讨论】: