【问题标题】:Simple "For" loop in PHP - SUM calculation of nested Array valuesPHP 中的简单“For”循环 - 嵌套数组值的 SUM 计算
【发布时间】: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 :(

【问题讨论】:

    标签: php arrays for-loop sum


    【解决方案1】:

    您创建两个随机数组,并打印第一个。由于您使用第二个进行计算,因此总和将不匹配(除非 md_rand 返回相同的结果)。我只是在 print are 之前移动了声明并使用了两次结果;其他一切正常。

    http://sandbox.onlinephpfunctions.com/code/071d4b964898fc4fcac96aa290e4d51c6a2458c8

    【讨论】:

    • Ahhh :) 天哪,新手喜欢犯什么错误。反正现在我完全明白了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多