1

我正在使用一个类对矩阵进行一些计算,在这种情况下:获取每列的总和。

总和输出是正确的,如果我隐藏通知,问题就解决了,但从逻辑上讲,我更喜欢更正。

在 PHP 5.3 中,我在这个函数中得到了一些通知:

Notice: Undefined offset: 0 
Notice: Undefined offset: 0 
Notice: Undefined offset: 1 

脚本

function sum()
    {
        foreach($this->numbers as $i => $rows)
        {
            foreach($rows as $j => $number)
            {
                $this->sum[0][$j] += $number; //notices here
            }
        }
        $the_sum = new matrix($this->sum, 1, $this->get_num_columns());

        return $the_sum;
    }

矩阵:

1     | 4

0.25  | 1



var_dump($this->numbers);
array
  0 => 
    array
      0 => int 1
      1 => float 4
  1 => 
    array
      0 => float 0.25
      1 => int 1

 $this->get_num_columns() // 2

任何想法来纠正这些通知?

谢谢

4

1 回答 1

3

是的,出现通知是因为您要添加数字的变量中没有初始值。在向其添加数字之前,您应该检查该数字是否存在并对其进行初始化。(注意,这不会改善您的结果,但初始化变量是一种好习惯)。

function sum()
    {
        foreach($this->numbers as $i => $rows)
        {
            foreach($rows as $j => $number)
            {
                if (!isset($this->sum[0][$j])) $this->sum[0][$j] = 0;
                $this->sum[0][$j] += $number; //no notices here
            }
        }
        $the_sum = new matrix($this->sum, 1, $this->get_num_columns());

        return $the_sum;
    }

不相关的考虑点

  • 正确的命名标准规定类名应该大写,以将它们与函数区分开来。所以你应该命名你的班级Matrix而不是matrix.
  • 如果你有机会,一个更好的解决方案是用 0 预先填充你的数组。array_fill()做得很好。
于 2011-11-19T19:11:33.687 回答