I have an array of divs (blog posts). Say 33 blog posts. My task is to split them first into pairs (wrap every other two divs by another) so that I had 17 divs (each containing a pair of blog posts, the last one may contain only one blog post) and then - I want these 15 pair-divs to be split again into groups of 5 (the last one again may contain fewer)... so that in the end I had 3 blocks each containing maximum of 5 blocks each containing two blog posts. Do I make myself clear enough?
Of course the total number of all the posts is unknown so I have to make it work automagically.
Searching for an answer I found out about the function named array_chunk which does exactly that - splits an array into arrays... in my case - I have to run this function twice. And it works perfectly :)
$posts = array( 1,2,3,4 ... 33 );
$pairs = array_chunk( $posts, 2 ) // $pairs will contain an array of 17 arrays each containing two elements
$wrap = array_chunk( $pairs, 5 ) // $wrap will contain an array of 3 arrays each containing an array of pairs
The only thing that bothers me is that when I output all the divs via foreach I happen to naturally have 3 nested foreaches... first to render 3 (or more) big wrappers - then - 5 pair wrappers and finally - a foreach to render two blog posts.
I am aware of another solution - to run a foreach once on an original array and arange some mathematical conditions (e.g. if( $i % 2 == 0 ) { //do stuff }) to open and close suitable divs at appropriate moments. Which I haven't been able to accomplish and would be really glad if someone could help me out with this one if this method is the one to follow.
My questions are as follows:
- Is there a significant difference (in terms of performance) as to how many nested foreaches to run?
- Is there some kind of a best practice as to which method to use in such situations? Or probably there is a totally different approach.