-3

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.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
sirlouis
  • 65
  • 1
  • 9

2 Answers2

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
  • if you wish to also start with an add, remove `$i > 0` clause – mschr Sep 02 '12 at 11:16
  • 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