开发者

foreach loop corrupting my array?

Explanation

I have a multidimensional array that is iterated over to created a categorized view of people with different research interests. The main array look something like this:

Array
(
    ...
    ['Cell Biology']      => Array(4 elements)
    ['Molecular']         => Array(6 elements)
    ['Biology Education'] => Array(14 elements)
    ['Plant Biology']     => Array(19 elements)  <--- Last element in array
)

I know that th开发者_JAVA百科e entire array is intact and correctly structured. The only information that is inside these array is an user id, like so:

Array ('Plant Biology') 19 elements
(
    [0] => 737
    [1] => 742
    [2] => 748
    ...
)

My problem is that after i run the main array through a foreach loop the last 'sub-array' gets messed up. By messed up I mean that what you see about instead look like:

String (13 characters) 'Plant Biology'

This is without doing at all anything inside the loop with to the array that gets corrupted.

Any tips to what it might be?

PHP Code

  // ---> Array is OK here
  echo "<h2>Research divided</h2>";
  // Loop areas and list them in 2 columns
  foreach($research['areas'] as $area => $areaArray) {
      // ---> Here it is already corrupted
      $count = count($areaArray);
      if($count > 0) {
          echo "<h3>$area</h3><hr/>";
          echo "<ul>";
          // Loop users within areas, divided up in 2 columns
          for($i=0 ; $i<$count ; $i++) {
              $uid = $areaArray[$i];
              echo "<li>$uid</li>";
          }
          echo "</ul>";
      }
  }


Are $area or $areaArray being used in different function elsewhere in your script? Wht happens if you rename them to $loop_area and $loop_areaArray to prevent accidental overwriting of variables?


It looks like an error that can occur if you loop over the array previously by referance using the same variable name for the value.

So if earlier in your code $areaArray is used in a foreach by referance it might corrupt your data.

Make sure both variables in your foreach are not used previously or unset them before the loop.

Check out:

http://bugs.php.net/29992

For more info on this kind of problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜