问题
If I give you an array
of objects, lets assume there are x number of objects how would you do the following using a grid system (bootstrap, foundation ... doesn't matter):
Loop Over the array and create something that replicates:
No I have been able to create this by doing:
echo "<div class='row'>";
for($i = 0; $i < count($options['fields']); $i++) {
// Increate the value of I and convert it from 1 to one.
$numberToWord = new FreyaTheme\NumberToWord\Conversion();
$wordRepersentation = $numberToWord->convert($i + 1);
if (isset($options['fields']['logo_image_' . $wordRepersentation])) {
if ($i <= 2) {
echo '<div class="medium-4 columns r3x1">';
echo '<img src="'.$options['fields']['logo_image_' . $wordRepersentation].'" />';
echo '</div>';
} else if ($i <= 6) {
echo '<div class="medium-3 columns r4x1">';
echo '<img src="'.$options['fields']['logo_image_' . $wordRepersentation].'" />';
echo '</div>';
} else if ($i <= 9) {
echo '<div class="medium-4 columns r3x1">';
echo '<img src="'.$options['fields']['logo_image_' . $wordRepersentation].'" />';
echo '</div>';
}
}
}
echo "</div>";
Now this, while a bit messy with the logic here - works for 10 items. Now imagine I give you 800. or 8 or 2 or 1 or ... you get the idea. Regardless of how many items I give you, this pattern, this box layout needs to repeat. I don't care if you give me 6 or 6000 objects.
I can do this with 10, but I don't know how to scale it. Ideas?
回答1:
Well this is one solution. Ofc you have to make it responsive yourself and use css classes instead of inline css:
<div style="padding: 5px; text-align:center;">
<?php
for($i = 0; $i < 5; ++$i)
{
?>
<div>
<?php
//output 3
if ($i%2 == 0)
{
for($cell=0;$cell<3;++$cell)
{
?>
<div style="display:inline-block; border:1px solid #000; width: 200px; margin-bottom: 10px;">
<span style="padding: 40px; display:inline-block; text-align:center;">350*150</span>
</div>
<?php
}
}
//output 4
else
{
for($cell=0;$cell<4;++$cell)
{
?>
<div style="padding: 5px; display:inline-block; border:1px solid red; width: 138px; margin-bottom: 10px;">
<span style="padding: 30px; display:inline-block; text-align:center;">350*150</span>
</div>
<?php
}
}
?>
</div>
<?php
}
?>
</div>
来源:https://stackoverflow.com/questions/31632266/how-do-display-a-layout-with-a-variable-number-of-items-in-an-array-php