Created
June 1, 2012 08:40
-
-
Save itsjavi/2850400 to your computer and use it in GitHub Desktop.
PHP function for grouping elements in a loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * PHP function for grouping elements in a loop | |
| * @param int $times Group max items | |
| * @param array $items | |
| * @param string $html_before Group start html | |
| * @param string $html_after Group close html | |
| * @param string $fn Callable function name that generates the item HTML | |
| * @param int $offset | |
| * @param int $limit | |
| * @return string The generated HTML (all groups) | |
| */ | |
| function group_every($times, $items, $html_before, $html_after, $fn, $offset=0, $limit = null){ | |
| $cursor = $cursor2 = $offset; | |
| $last = !empty($limit) ? $limit : count($items); | |
| $last-=1; | |
| $html = ""; | |
| while($cursor <= $last){ | |
| echo $html_before; | |
| for($i = $cursor; $i < ($cursor + $times); $i++){ | |
| $cursor2 = $i; | |
| if($cursor2 > $last) break; | |
| $html .= call_user_func($fn, $i, $items[$i]); | |
| } | |
| $cursor = $cursor2+1; | |
| echo $html_after; | |
| } | |
| return $html; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: