I am getting two different arrays arrays of data from MSQL database, first array from my blog post table containing 15 rows/items, and the second array from advert table containing 3 rows/item. i want to foreach the first 5 set of data from blog post table(the first array), then foreach 1 (one) from advert table (second array) and continue from where i stopped in the first array with another 5 item and one from the first array, just like that. Please help me come up with PHP code on how to do that. thank you.
Asked
Active
Viewed 260 times
-3
-
1You might start by telling us for what programming language you use – Sean Patrick Floyd Sep 02 '12 at 10:34
-
Please i need PHP code to do that – sirlouis Sep 02 '12 at 10:57
-
1[What have you tried?](http://whathaveyoutried.com) – Sep 02 '12 at 11:10
-
foreach blog_array where i%5 == 0 etc. etc. where are your tut books ? – Sreenath S Sep 02 '12 at 11:18
2 Answers
0
use modulo.
you will have a count with mssql_num_rows
, then iterate a counter, say $i
then in foreach($rows)..:
$i = 0; $count = mssql_num_rows($result);
foreach($rows as $blog) {
if($i > 0 && $i++ % 5 == 0) {
$advert = array_shift($adverts_array);
// process $advert
}
// process $blog here
}

mschr
- 8,531
- 3
- 21
- 35
-
-
Thanks for your assistance, but I tried the above scripts it outputs 5 from the posts array as expected, the problem now is dat its does no echo the array values of the advertisement array and when I use foreach for the advertisement array it prints all the advertisement content before continuing that of the post array, please how do I fix this?? – sirlouis Sep 02 '12 at 20:26
-
couldnt say why from the info youve provided.. but you have two resultsets to iterate right? then simply process the first advert @ count 5, second advert @ count 10 etc. thats why the comment says 'take one(!)' – mschr Sep 02 '12 at 21:50
0
The code assumes arrays are indexed starting from 0
.
$i = 0;
foreach ($posts as $post) {
// Output and/or otherwise process $post
if (++$i % 5 == 0) {
$advertisements[$i / 5 - 1] // Output and/or process advertisement
}
}

galymzhan
- 5,505
- 2
- 29
- 45
-
Thanks for your assistance, but I tried the above scripts it outputs 5 from the posts array as expected, the problem now is dat its does no echo the array values of the advertisement array and when I use foreach for the advertisement array it prints all the advertisement content before continuing that of the post array, please how do I fix this?? – sirlouis Sep 02 '12 at 20:24