未定义的偏移量:php中为9?

时间:2018-09-20 08:09:32

标签: php

我正在尝试添加当月的销售额并将其显示在表格上。一切正常,但警告消息显示未定义偏移:9。

图片为:enter image description heIe

请检查代码我在做什么:

$thisyear = $db->query("SELECT total_Price,order_date FROM orderTable WHERE YEAR(order_date) = '{$thisyear}'");

 $current = array();
 $currentTotal = 0;

 while($x = mysqli_fetch_assoc($thisyear)){
 $month = date("m-d-Y",strtotime($x['order_date']));

 //The Below line showing Error
 $current[(int)$month] += $x['grand_total']; // This line showing Error

 $currentTotal += $x['total_Price'];
 }

使用此代码,我得到正确的结果。它会添加月销售额并将其显示在表格上,但同时还会显示警告消息。

请提出我的错。

3 个答案:

答案 0 :(得分:1)

$current[(int)$month]是您要写入的数组项目,但是由于使用+=操作,因此要添加到现有项目中。该行实际上意味着:

$current[(int)$month] = $current[(int)$month] + $x['grand_total']; 

这意味着您不仅要写第9月的书,还要读它,而且显然$current中还没有该月。

由于您根本没有初始化$current的任何项目,因此我认为查询返回的第一项是第9个月,因此它是第一次失败的迭代。

可能的解决方案:

  • 通过添加所有月份来初始化$current,每个月份的默认值为0。
  • 添加之前,请检查月份是否存在,如果不存在,请对其进行初始化。
  • 使用三元表达式,甚至使用一些警告抑制来尝试读取月份值,如果失败,则默认为0。

我会去第一个,因为它是最透明的。

答案 1 :(得分:1)

由于$monthdate("m-d-Y",strtotime($x['order_date']));,因为它将以 09-20-2018 格式的日期结尾,所以将类型强制转换为int会错误(如果没有失败的话) 。 相反,您可以这样做。

$mm = date("m",strtotime($x['order_date']));
if (!isset($current[$mm])) {         //or !isset($current[(int)$mm])
    $current[$mm] = 0;               //or $current[(int)$mm] = 0;
}
$current[$mm] += $x['grand_total'];  //or $current[(int)$mm] += $x['grand_total'];

这将消除错误,因为+=运算符认为它是先前设置的(不是),从而显示警告,提示您之前未设置。

答案 2 :(得分:0)

由于最初未设置$current[(int)$month]而导致行抛出警告

执行以下操作:-

$thisyear = $db->query("SELECT total_Price,order_date FROM orderTable WHERE YEAR(order_date) = '{$thisyear}'");

$current = array();
$currentTotal = 0;

while($x = mysqli_fetch_assoc($thisyear)){
    $month = (int)date("m",strtotime($x['order_date']));

    $current[$month] = isset($current[$month]) ? $current[$month]+$x['grand_total'] : $x['grand_total'];

    $currentTotal += $x['total_Price'];
}

注意:-+=运算符的意思是在现有内容中添加一些内容,但您的案例索引9尚未在此处预先设置

相关问题