0

我有以下代码:

$chart_data = array();
foreach ($range as $range_day) {
  foreach ($numbers as $number) {
    if($range_day == $number['date']){
      @$chart_data[$range_day] += $number['events'];
    } else {
      if(isset($chart_data[$range_day])){
        $chart_data[$range_day] += 0;
      }
    }
  }
}

这一行:$chart_data[$range_day] += 0;给了我一个未定义的索引错误,所以我添加了isset检查,但它没有设置,所以它破坏了我的数组。我知道它没有设置,我不在乎,但我通篇读到@解决方案的味道很差。如何以正确的方式消除错误?

4

3 回答 3

1

您是否看过array_key_exists函数: http: //php.net/manual/en/function.array-key-exists.php

就像是:

$chart_data = array();
foreach ($range as $range_day) {
  foreach ($numbers as $number) {
    if(!array_key_exists($range_day, $array)) {
      $chart_data[$range_day] = 0;
    }
    if($range_day == $number['date']){
      $chart_data[$range_day] += $number['events'];
    }
  }
}
于 2012-05-25T21:15:35.130 回答
1

您可以在开始时将其设置为零:

$chart_data = array();
foreach ($range as $range_day) {
  $chart_data[$range_day] = 0;
  foreach ($numbers as $number) {
    if($range_day == $number['date']){
      $chart_data[$range_day] += $number['events'];
    } else {
      if(isset($chart_data[$range_day])){
        $chart_data[$range_day] += 0;
      }
    }
  }
}
于 2012-05-25T21:15:53.907 回答
1

您可以检查它是否设置,然后设置它:

foreach ($numbers as $number) {
    if (!isset($chart_data[$range_day])) {
        $chart_data[$range_day] = 0;
    }
    if ($range_day == $number['date']) {
        $chart_data[$range_day] += $number['events'];
    } else {
        $chart_data[$range_day] += 0; // you're just adding 0 so why have this line at all?
    }
}

此答案假定有$range可能包含重复项$range_day,因此它不会覆盖$chart_data.

于 2012-05-25T21:17:19.917 回答