php版本升级注意事项
我正在使用一个类对矩阵进行一些计算,在本例中:获取每列的总和。
总和输出是正确的,如果我隐藏通知,问题就解决了,但逻辑上,我更喜欢更正。
在 PHP 5.3 中,我在此函数中收到一些通知:
Notice: Undefined offset: 0
Notice: Undefined offset: 0
Notice: Undefined offset: 1
script
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;
}
Matrix:
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
有纠正这些通知的想法吗?
谢谢
i am using a class to make some calculations with matrices, in this case: Get the sum of each column.
The sum output is correct, and if I hide the notices, the problem is solved, but logically, i prefer the correction.
In PHP 5.3 I get some notices in this function:
Notice: Undefined offset: 0
Notice: Undefined offset: 0
Notice: Undefined offset: 1
script
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;
}
Matrix:
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
and
$this->get_num_columns() // 2
Any idea to correct these notices ?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,出现该通知是因为您要添加数字的变量中没有初始值。在添加号码之前,您应该检查该号码是否存在并对其进行初始化。 (请注意,这不会改善您的结果,但初始化变量是一个很好的做法)。
需要考虑的不相关点
Matrix
而不是matrix
。array_fill()
执行以下操作:干得好。Yes, the notice occurs because there is no initial value in the variables you are adding numbers to. You should check if the number exists and initialize it before you add a number to it. (Note, this won't improve your result, but it is good practice to initialize variables).
Unrelated Points to Consider
Matrix
and notmatrix
.array_fill()
does the job nicely.