使用 PHP 的未定义数组键 1

Undefined array key 1 using PHP

提问人: 提问时间:4/15/2022 最后编辑:Ryan M 更新时间:4/15/2022 访问量:4548

问:

您好,我有警告“未定义的数组键 1”。我var_dumped数组,这就是结果。我想问你我该如何解决它?我尝试array_values功能,但什么也没发生。我使用PHP

array(0) { } 
array(1) { [1]=> array(2) { ["sum"]=> int(26140) ["count"]=> int(1) } } 
array(1) { [1]=> array(2) { ["sum"]=> int(52365) ["count"]=> int(2) } } 
array(1) { [1]=> array(2) { ["sum"]=> int(78510) ["count"]=> int(3) } }

添加更多代码。警告适用于最后 2 行

$array_months = array();

  foreach($array as $value) {
    if ($value == null) {
      continue;
    }
    $parts = explode('|', $value);
    $datum = explode ('.', $parts[0]);
    $month_int = (int) $datum[1];
    $value_thousand = str_replace (',', '',$parts[1]);
    $value_int = (int) $value_thousand;
    unset($array_months[0]);
    var_dump($array_months);
    $array_months[$month_int]["sum"] = ($array_months[$month_int]["sum"] + $value_int);
    $array_months[$month_int]["count"] = $array_months[$month_int]["count"]+1;
  }
php 数组 警告 var-dump

评论

0赞 Eddy 4/15/2022
请分享更多细节。共享您尝试获取数组索引 1 的代码
4赞 Barmar 4/15/2022
这些是 4 个不同的数组。第一个是空的,因此任何数组索引都会出错。

答:

0赞 Kazz 4/15/2022 #1

在 foreach 循环的第一次迭代期间和赋值行处:

$array_months[$month_int]["sum"] = ($array_months[$month_int]["sum"] + $value_int);

首先评估右侧,此时它是空的,因此您无法读取它的元素,因为它还不存在,再进一步调用它不再是空的,并且您不会多次收到警告。由于在您的情况下等于 1,因此该行根本不执行任何操作,如果您有,或者您将在每次迭代时收到警告。$array_months$month_int$month_intunset($array_months[0]);unset($array_months[1]);unset($array_months[$month_int]);

针对您的特定情况的实际修复是这样的:

// check if there is already element/item for $month_int month present in our array
if(isset($array_months[$month_int])){
    // if so we can read previous data and sum/count them
    $array_months[$month_int]["sum"] = ($array_months[$month_int]["sum"] + $value_int);
    $array_months[$month_int]["count"] = $array_months[$month_int]["count"]+1;
}else{
    // when there isn't any record of current month we have to create the first one
    // (there is nothing to sum or count to yet)
    $array_months[$month_int]["sum"] = $value_int;
    $array_months[$month_int]["count"] = 1;
    // since here is no reading of nonexistent element there is no error now
}