tags:

views:

49

answers:

2

is it possible to use the indexes values inside of a foreach loop that is contained inside a partent for each. Look at the script below and observe that in the child for each I use echo'<div>' .$product['name'] . '</div>'; When $product[' name ']; belongs to the parent for each. is that possible? I am looking to use the index ['name '] in the child foreach().

foreach($tree as $product){

    echo '<div>' . $product['name']. '</div>';

    foreach($product['variery'] as $variety) 

    {
        echo'<div>'. $variery['image'] . '</div>';
        echo'<div>' .$product['name'] . '</div>';

    } // end of child for each

} //end of parent for each
+2  A: 

Yes, it is possible.

Even outside of the loop the $product is defined (the last value keeps assigned).

Question from comments: Can I also do this?

value="', $variety['price'], $variety['variety'], $product['name'],'";

the above codee would go inside the child loop.

Answer: Yes, but this syntax will lead to error. To use associative array in the double quotes skip the single quotes.

value="', $variety[price], $variety[variety], $product[name],'";

Or use dots:

value="', " . $variety[price] . ", " . $variety[variety] . ", " . $product[name] . ",'";
Petr Peller
Can I also do this? value="', $variety['price'], $variety['variety'], $product['name'],'" the above codee would go inside the child loop.
jona
A: 

Yes, if you define a variable in a parent loop, then it will retain its value in any child loops, AS LONG AS those child loops do not themselves redefine the variable. As far as your inner loop is concerned, $product is a "local" constant for the life of the loop, so $product['name'] and $product['variery'] will not change until the next iteration of the outer loop.

As a minor performance tip, you do not have to do string concatenation within your echo statements. echo will accept multiple comma-separated values. The following will work exactly the same and not have the overhead of two concatenations:

echo '<div>', $product['name'], '</div>'; // notice the commas

It's minor, but if this becomes a heavily traveled code path, any cycles saved are a good thing.

Marc B
Marc you mean that instead of something like value="' . $variety['price'].'_'. $variety['variety']. '_'$product['name'].'" I can easely do it by comman-separated values like:value="', $variety['price'], $variety['variety'], $product['name'],'"
jona
The value below will go inside the foreach child loopvalue="', $variety['price'], $variety['variety'], $product['name'],'"
jona
No, the comma separation only applies to the echo command. But the rest holds. As long as you don't overwrite the $product variable inside child loops, it will have the same value for all iterations of the child loop.
Marc B