我怎样才能打断foreach语句,重复其他内容,然后继续


How can i break a foreach statement, echo something else and then continue

我从MSQL数据库中获得两个不同的数据数组,第一个数组来自我的博客文章表,包含15行/项,第二个数组来自广告表,包含3行/项。我想foreach博客文章表(第一个数组)中的前5组数据,然后foreach广告表(第二个数组)的第1组数据,并从我在第一个数组中停止的地方继续使用另5个项目和第一个数组的一个项目,就像那样。请帮我想出如何做到这一点的PHP代码。非常感谢。

代码假设数组从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
  }
}

使用模。

您将使用mssql_num_rows进行计数,然后迭代计数器,例如$i

然后在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
}