开发者

Simple and idiot loop that I can't figure how to do it

I have to iterate over an array and display its items. I have to paginate it so I can render a paginator. The paginator structure is something like:

<div class='paginator'>
    <div class="page">
        <img src="path/to/picture"/>
        <img src="path/to/picture"/>
        <img src="path/to/picture"/>
        <img src="path/to/picture"/>
    </div>
    <div class="page">
        <img src="path/to/picture"/>
        <img src="path/to/picture"/>
        <img src="path/to/picture"/>
        <img src="path/to/picture"/>
    </div>
</div>

Finally, I have a PHP array with the paths. I want something like this:

echo "<div class='paginator'>";
for ($i = 0; $i < 3; $i++) {
   echo "<div class='page'>";
   for($j = 0; $j < 4; $j++) {
      echo "<img src='" . $arr[$i * $j] . "'/>"     
   }
   echo "</div>
}
echo "</div>";开发者_Python百科

But, it doesn't work. I'm doing the loops incorrectly and I can't figure out how they should be.


Assuming yours is not just a simple sintax problem I think you need $arr[$i * 4 + $j] instead of $arr[$i * $j]
Where "4" is the size of each row.
Look at this example

0  1  2  3 (4 elements in this row which starts from 0)
4  5  6  7 (this row starts from 4)
8  9 10 11 (this starts from 4 * 2)

Each row starts with 4 (number of elements per row) multiplied for the number of the row (starting from 0). To iterate each element in the row you have to add the index of the element in the row ($j in your example) so: $index = $row_index * $elements_per_row + $column_index


echo "<div class='paginator'>";
for ($i = 0; $i < 3; $i++) {
   echo "<div class='page'>";
   for($j = 0; $j < 4; $j++) {
      echo "<img src='" . $arr[$i * $j] . "'/>";
   }
   echo "</div>";
}
echo "</div>";

You forgot semicolons and quote.


It looks like you're trying to multiply the $i and $j variables, which probably isn't what you want:

echo "<img src='" . $arr[$i * $j] . "'/>"

What you need to put here will depend on the structure of the $arr array. Do you mean:

$arr[$i][$j]

That would work for an array with this structure (just an example):

$arr[0][0] = 'page 1 image 1';
$arr[0][1] = 'page 1 image 2';
//....
$arr[1][3] = 'page 2 image 4';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜