开发者

display ['name'] inside of a foreach loop coming from another loop

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>';
       开发者_如何学JAVA echo'<div>' .$product['name'] . '</div>';

    } // end of child for each

} //end of parent for each


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] . ",'";


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜