1

I have a problem with embeded html in foreach loop: HTML:

<div class="head">
<div class="wins">
    <div class="images"> 
        <a href="#"><img src="images/1.jpg" alt=""></a>
        <a href="#"><img src="images/2.jpg" alt=""></a> 
        <a href="#"><img src="images/3.jpg" alt=""></a> 
    </div>
    <div class="Bar"> 
        <a href="#" rel="1"><span>1</span>Cat1</a>
        <a href="#" rel="2"><span>2</span>Cat2</a> 
        <a href="#" rel="3"><span>3</span>Cat3</a> 
    </div>
</div>

I want to print html with this function :

function Bar($array){
    $box .= '<div class="images">';
    foreach($array as $key => $value){
       $box .= ' <a href="#"><img src="'.$value['image'].'" alt=""></a>';
    }
    $box .= '</div>';
    return $box;
 }

I want to break the loop after <div class="images"> and continue loop after the <div class="Bar"> . But Im confusing about this issue. Please show me the right way. Thanks in advance

3 Answers 3

2

Two options:

Run through the loop twice.

or

Store each section in a separate variable and merge them later on, i.e.

function Bar($array){
    foreach($array as $key => $value){
       $images .= ' <a href="#"><img src="'.$value['image'].'" alt=""></a>';
       $bar .= ' <a href="#"><span>....</a>';
    }
    $box .= '<div class="images">';
    $box .= $images;
    $box .= '</div>';
    $box .= '<div class="Bar">';
    $box .= $bar;
    $box .= '</div>';
    return $box;
 }
Sign up to request clarification or add additional context in comments.

Comments

1
function Bar($array){  
$divImage=$divBar=array();  
    foreach($array as $key => $value){  
       $divImage[]= " <a href='#' ><img src='{$value['image']}' alt=''></a>";  
       $divBar[]= " <a href='#' rel='$key' ><span>$key</span>Cat$key</a>";  
    }  
 $divImage="<div class='images'>".implode("\r\n",$divImage)."</div>";  
 $divBar="<div class='bar'>".implode("\r\n",$divBar)."</div>";  
    $box="<div class='wins'>  
   $divImage  
   $divbar  
    </div>";  
   return $box;  
 }  

Comments

0

maybe something like that?

$divimg = '<div class="images">';
$divbar = '<div class="Bar">';

foreach(...) {
    $divimg .= ' ... ';
    $divbar .= ' ... ';
}

$divimg .= '</div>';
$divbar .= '</div>';

$divimg .= $divbar;

return $divimg;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.