首页 > 解决方案 > 帕斯卡的三角形有效但抛出了一个通知

问题描述

这是我的脚本。$tri当我这样做时,程序无法在数组中找到值$somma=$tri[$y]+$tri[$z];

我不断收到通知,但为什么呢?

<?php
$tri=array(1,1);
for ($x=0;$x<=6;$x++) {
    print_r($tri);
    $count=count($tri);
    $trinew=array();
    for($y=0;$y<$count;$y++) {
        $z=$y+1;
        $somma=$tri[$y]+$tri[$z];    // <-- here is the problem
        array_push($trinew,$somma);
    }
    array_unshift($trinew, 1);
    $tri=$trinew;
}
?>

标签: phparraysfor-loopnoticepascals-triangle

解决方案


$y= $count - 1,然后$z=$count并且永远没有可用的元素 via $tri[$z]

例如,在 的第一次迭代中$x$tri是:

array (
  0 => 1,
  1 => 1,
)

何时一切都很好$y = 0$z = 1但是当嵌套for()移动到其最终迭代($y = 1$z = 2)时,$tri没有2索引。

这就是您收到通知的原因。


使用空合并运算符和其他一些小改动,这似乎运行顺利:

代码:(演示

$tri = [1, 1];
for ($x = 0; $x <= 6; ++$x) {
    var_export($tri);
    $trinew = [1];
    for($y = 0, $count = count($tri); $y < $count; ++$y) {
        $z = $y + 1;
        $trinew[] = $tri[$y]  + ($tri[$z] ?? 0);
    }
    $tri = $trinew;
}

或者您可以将一个0元素推入$tri内部 for 循环之前并从count(). https://3v4l.org/sWcrr


推荐阅读