0

I have a piece of code which reads an XML catalog file with SimpleXMLElement and prints out the containing products of that catalog into a css styled table on a website.

The code outputs every product next to each other. However I only want to show 4 products in a row.

I therefore need to insert some

<tr> </tr> 

tags following every 4 (or x) number of products in the array.

How should I do this? My code is as follows:

echo '<table class="products">';

foreach (getProdutcsFromCatalog($grpName) as $product) {


                        $output = '

                        <td>
                            <h2>' .$product->title .'</h2>
                            <div class="img">
                                <img src="' .$product->img . '" height="150" width="100" class =""/>
                            </div>  
                            <div>
                                '.$product->description.'
                            </div>
                            </div>
                            <div class="price">
                                <b>
                                    '.$product->price . ' DKK' . ' 
                                </b>
                            </div>
                            <div class="addToCart">
                                <a href="#">Læg i kurv</a>
                            </div>
                        </td>   

                        ';

                        echo $output;
                    }

                echo '</table>';
2
  • I don't see any tr tags. Commented Feb 21, 2013 at 20:44
  • That's because I can't figure out where and how to place them so I get the result that i want. My question is how should I add these tags. Commented Feb 21, 2013 at 21:18

2 Answers 2

1

Initialise $i = 0; before starting the foreach loop. Then change your

    echo $output;
}

to:

    if( $i % 4 == 0 ) echo "<tr>";
    echo $output;
    if( $i % 4 == 3 ) echo "</tr>";
    $i++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for this simple and effective solution. I've tried so many different and more advanced methods - not of them working properly. What does the % mean?
The % is an arithmetic operator, known as modulus. It returns the remainder. Here, read this on docs.
0

If you only want 4 items per row I'd advise you to first loop through the XML structure and save all your items in an array, and then to array_chunk($items, 4) the array and then loop through it and generate the table.

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.