Abdullah Rasheed
Abdullah Rasheed

Reputation: 3752

Assistance with Logic for nested loop in php

Let's say I have 8 php objects and I need to iterated through them and output various information into html differently according to their placement. I have developed the structure for the css and html and you can see it here: http://jsfiddle.net/v3qcc/9/ I just need help with the logic of placing them their dynamically.

I need to take every two objects and place them in this wrapper:

<div class="col">
    <div class="third">
        <div class="col-content">         
          **...Object One Here**
        </div>
    </div>

    <div class="fourth">
        <div class="col-content">         
          **...Object Two Here**
        </div>
    </div>
</div>

<div class="col">
    <div class="third">
        <div class="col-content">         
          **...Object Three Here**
        </div>
    </div>

    <div class="fourth">
        <div class="col-content">         
          **...Object Four Here**
        </div>
    </div>
</div>

Upvotes: 0

Views: 189

Answers (3)

Stv
Stv

Reputation: 506

try this :

<?php

echo '<div class="col">';

for ($i=0; $i<$max_elements; $i++)
{
    $class = ($i&1) ? "third" : "fourth";

    echo '<div class="'.$class.'">
              <div class="col-content">         
               **...Object num : '.$i.' Here**
              </div>
         </div>';
}

echo '</div>';

Upvotes: 1

Cups
Cups

Reputation: 6896

// heres a class
class thing {
public $ybob = 23;
}

// create an array of 8 of them
$i = 0;
$a= array();
while(8> $i){
$a[$i] = new thing;
$i++;
}
//var_dump($a);

// loop thru the array of objects
$rows = 1;
foreach($a as $ob){

// use modulus operator to work out if a row is odd or even
echo ( ($rows % 2)  === 1 ) ?  '<br />NEW ROW' : '' ;
echo $ob->ybob . ' - ' ;  // output the objects data in any case
$rows++;
}

In the ternary operator 4 rows up, you can add the extra row tag, or revert an if/else if you wanted to use many more lines of markup.

Gives:

NEW ROW 23 - 23 - 
NEW ROW 23 - 23 - 
NEW ROW 23 - 23 - 
NEW ROW 23 - 23 -

Upvotes: 1

kzrdt
kzrdt

Reputation: 532

Personnaly, I'll test an indicator incremented each time in my loop if it's even or odd and display the template needs according to this.

Upvotes: 0

Related Questions