user2017772
user2017772

Reputation: 13

How to split into table rows

I've tried many solutions given here but I can't manage to split this piece of code into multiple table rows. Many thanks in advance!!

Update: Sorry if my question wasn't clear. I want to have 5 cols and start a new table row after that hope this helps. Thanks for all the answers!

Update2: Somebody who can help me out here? The code from Minesh is close but I still get errors, see comments below. Many, many thanks in advance!!

$opties.='<b>'.$option['name'].':</b><br /><table><tr>';

      foreach ($option['option_value'] as $option_value) { 

        $opties.= '<td><img src="image/cache/'.$option_thumb.'" /><br />'.$option_value['name'].'</td>';

      }
       $opties.='</tr></table>';

Upvotes: 0

Views: 2503

Answers (4)

Minesh
Minesh

Reputation: 2302

That is because in loop you are only putting TD and not TR. You need to maintain counter which is incremented in each loop by 1.

Then inside foreach loop, you can check using modulo operator if 4 columns are printed you need to complete TR tag and start new TR tag.

@UPDATED: Based on user's comment of 5 cols

See below code :

$opties.='<b>'.$option['name'].':</b><br /><table><tr>';
$cnt=0;
foreach ($option['option_value'] as $option_value) { 
    if($cnt % 5 == 0 && $cnt > 1) 
        $opties .= '</tr><tr>';
    $opties .= '<td><img src="image/cache/'.$option_thumb.'" /><br />'.$option_value['name'].'</td>';
    $cnt++;
}
if(count($option['option_value']) % 5 > 0)
    $opties.='</tr>';
$opties.='</table>';

Upvotes: 2

bradym
bradym

Reputation: 4961

I can't tell what your array contains, so I'm giving you a more generic example.

$array  = array(1,2,3,4,5,6,7,8,9,10);
$chunks = array_chunk($array, 5);
$output = '<table>' . PHP_EOL;

foreach ($chunks as $row) {
    $output .= '<tr>';

    foreach ($row as $col) {
        $output .= '<td>' . $col . '</td>';
    }

    $output .= '</tr>' . PHP_EOL;
};

$output .= '</table>';

echo $output;

This is just a slightly different take on @Piya's answer.

Upvotes: 0

Piya Pakdeechaturun
Piya Pakdeechaturun

Reputation: 141

First of all

you should have 2 loops

foreach($opties as $rows => $column)
    //now it's row so echo 
    <tr>
    foreach( $column as $key => $value) {
        // now it's <td> turn
        <td> data </td>
    }
    </tr>
}

This is just pseudo code to explain the 2 loops

Hope this help ;)

Upvotes: 0

Mateusz Rogulski
Mateusz Rogulski

Reputation: 7455

I'm not sure if it's what you're looking for but try:

$opties.='<b>'.$option['name'].':</b><br /><table>';

      foreach ($option['option_value'] as $option_value) { 

        $opties.= '<tr><td><img src="image/cache/'.$option_thumb.'" /><br />'.$option_value['name'].'</td></tr>';

      }
$opties.='</table>';

Couse if you want to create multiple rows you must use <tr> tag inside your foreach loop.

Upvotes: 1

Related Questions