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>";
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
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