dongqin8652 2016-07-18 10:06
浏览 51
已采纳

从中删除元素后迭代数组时出现未定义的偏移量错误

I receive the following error message:

Undefined offset: 1

It points to this block of code:

    $nbrProgrammingsRemoved = 0;
    for($i = 0; $i<count($this->products); $i++){
       if((($this->products[$i])->id)==$id){
          array_splice($this->products, $i, 1);
          for($j = 0; $j<count($this->programming); $j++){
     /*ERROR LINE*/ if((($this->programming[$j]->out_prod_id)==$id) || (($this->programming[$j]->in_prod_id)==$id)){
                $nbrProgrammingsRemoved++;
                array_splice($this->programming, $j, 1);
             }
          }
          return true;
       }
    }
    return false;

Specifically, the error points to the innermost if-statement. (The one with "||" in it).

Now, important to note is that this error does not always occur. It only ever happens after the following code has been run:

foreach ($this->programming as $key => &$prog) {
   if($prog->in_prod_id == $in_prod_id){
      if($prog->in_index == $in_index){
         unset($this->programming[$key]);
      }
   }
}

The purpose of this code is to iterate through my objects in my array and remove those associated with a certain ID. This does appear to work since the output on my website is as expected. It's only when I, after doing this, attempt to execute the first code-block that my error occurs.

I've tried troubleshooting this for a while now, but without success. Any ideas? Any more information that you need me to post?

Edit: For further clarification, if needed, the 1st code block iterates through an array to remove a single element of a specified ID. The 2nd code block iterates through another array and removes several elements.

  • 写回答

1条回答 默认 最新

  • dongshui2254 2016-07-18 10:35
    关注

    As far as I understand, you have an array with indexes comming in a sequence:

    $programming = array(
        0 => ...,
        1 => ...,
        2 => ...,
    );
    

    At some point you unset one element, so you array looks like this:

    $programming = array(
        0 => ...,
        2 => ...,
    );
    

    And then you're using a for loop to iterate over all numbers from 0 up to N-1 (0, 1, 2, 3, 4 ... to be precise) presuming that all indexes are filled.

    I think the best solution is to use a foreach loop in this case as it will care about indexes automatically and bypass deleted items.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧