Foreach里面的foreach Strange Bug

Foreach里面的foreach Strange Bug

问题描述:

<?php
    foreach($products as $product){
      //some code here , echoing products and everything works there
      foreach($types as $type){
        echo $type['type'];
        // only does the echo on the first occurence of this "types" loop
      }
    }
?>

Hi everyone,

I'm making a type of form in order to allow people, for each product of the database, to specify the type of the product.

$products and $types are both distinct arrays. Products contains all my products and $types contains all my types.

Actually I have only 2 products and 2 types.

So, my question is: Why the echo doesn't show anything for the second occurence of the foreach($products as $product), and show the good results at the first occurence?

This is exactly the same array, called 2 times, but working only at the first occurence of the loop. Very Strange for me.

Hope you'll understand despite my poor english. Bye

Let's assume there are 4 products and 7 types. With the following code you are executing the outer loop 4 times and the inner loop 7 times. What is printed is the content of $type['type'] for all 7 items. And this 4 times.

<?php
    foreach($products as $product){
        foreach($types as $type){
         echo $type['type'];
        }
     }
?>

What you need is a $products array that contains the types for the product, so that you can use the following code

<?php
    foreach($products as $product){
        foreach($product->type as $type){
         echo $type['type'];
        }
     }
?>

This happens because on the second loop, $type is still a reference to the last array item, so it's overwritten each time.

You can see it like that:

$types = array ('type-one','type-two','type-three');

foreach ($types as $type) {
    echo $type;
}

foreach ($types as $type) {
    echo $type;
}

As you can see, the second time you call the array. It will not echo anything.

There is no "bug" in your code. It just happens like that

To solve it. You can use this code before the second loop. It will reset the array reference.

reset($types);