Kyle Darin
Kyle Darin

Reputation: 13

How do I evenly distribute data into 4 columns in php?

I am making a project in PHP that pulls pictures from a Facebook page using Facebook SDK. I am using a loop to echo 40 different images, I want to distribute these images evenly between 4 different bootstrap columns as shown below.

Column1     Column2     Column3     Column4
Image1      Image2      Image3      Image4
Image5      Image6      Image7      Image8

The loop I am currently using to echo images into one column:

  foreach($rData as $post) {
   $image = ('<center><img class="img-responsive" src="'.$post->getProperty('full_picture').'"/>'.'</br></center>');
   print('<div class="col-sm-12">'.$image.'</div'); 
  }

I've spent quite some time trying to figure this out but can never seem to distribute the data without having it repeat. Any help would be appreciated, thanks in advance.

Upvotes: 1

Views: 868

Answers (3)

nilobarp
nilobarp

Reputation: 4084

Using array_chunk:

foreach(array_chunk($rData, 4) as $chunk)
{
    print('<div class="row">');
    foreach($chunk as $post) {
       $image = ('<center><img class="img-responsive" src="'.$post->getProperty('full_picture').'"/>'.'</br></center>');
       print('<div class="col-sm-3">'.$image.'</div>'); 
    }
    print('</div>');
}

Upvotes: 0

Jeff Lambert
Jeff Lambert

Reputation: 24661

Change:

print('<div class="col-sm-12">'.$image.'</div'); 

To:

print('<div class="col-sm-3">'.$image.'</div'); 

Bootstrap uses a 12-column grid. If you tell each element to only take up 3 of those columns, then you will get 4 across on a larger screen.

See also this answer to help you determine how far down in screen size you want to keep those 4 columns before you reach a break point.

Upvotes: 2

Guilherme Ferreira
Guilherme Ferreira

Reputation: 143

You can check when is the last element (4) in your line, and put something (html element) to broken to the next line:

$i = 0;

foreach($rData as $post) {
    $myDivisor = '' //nothing yet

    if( ($i%4) == 0 )
        $myDivisor = 'something...';

    $image = ('<center><img class="img-responsive" src="'.$post->getProperty('full_picture').'"/>'.'</br></center>');

    print('<div class="col-sm-12">'.$image.'</div>'.$myDivisor);

    $i++;

...

Upvotes: 0

Related Questions