duanguan1573 2018-03-25 20:24
浏览 36
已采纳

PHP中简单的“For”循环 - 嵌套Array值的SUM计算

I can't understand why my simple FOR loop in PHP can't properly calculate SUM of nested Array values (integers).

Anyone can help me understanding this?

Sandbox: 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 :(
  • 写回答

1条回答 默认 最新

  • drj58429 2018-03-25 20:32
    关注

    You create two random arrays, and print the first one. Since you use the second for your calculation, the sums won't match (unless md_rand returns the same result). I simply moved the declaration before the print are and used the result twice; everything else works fine.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等