0

我有同一个数组的内循环,但是在内循环中我删除了一些元素,新数组被分配给主数组,但出现主循环索引仍然不变的问题!

foreach ($newsletters as $index=>$mainNewsletterObj) {
    // var_dump($newsletters); // it prints new DATA !

         // the problem is here !
    echo 'up index is '.$index .'<br/>';  // it prints old index!!!!!!!!!!

      // make a copy of main array
      $newslettersArray = $newsletters; 

        //inner loop
     foreach ($newslettersArray as $key => $newsletterObj) {

    if ($newsletterObj['month'] == 3 );

         unset($newslettersArray[$key]);  //remove element
      } else
      {
     // make a new array of modified one to start index from 0
     $newslettersArray1 = array_values($newslettersArray); // to start index from 0

      // assign new modified array to the original one
     $newsletters = $newslettersArray1;

  }

}   // end inner loop

$index=0;
  echo 'down index is '.$index .'<br/>';  // it prints 0
 }  // end of outer loop

任何帮助都非常感谢!

4

2 回答 2

0

不要更改原始数组!在进入循环之前创建该数组的副本,然后在必要时从副本中删除元素。

于 2013-04-03T09:07:54.367 回答
0

使用while (list($index, $mainNewsletterObj) = each($newsletters))而不是foreach ($newsletters as $index=>$mainNewsletterObj)

于 2013-04-04T10:43:44.920 回答