首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在循环中显示不同的数组元素

在循环中显示不同的数组元素
EN

Stack Overflow用户
提问于 2014-04-25 12:22:44
回答 1查看 102关注 0票数 0

我有一组对象:

代码语言:javascript
运行
复制
Array
(
    [0] => stdClass Object
        (
            [id] => 24
            [ban_id] => 163
            [ban_url] => http://www.website.com/wp-content/uploads/2014/04/72890.jpg
        )

    [1] => stdClass Object
        (
            [id] => 25
            [ban_id] => 162
            [ban_url] => http://www.website.com/wp-content/uploads/2014/04/46860.jpg
        )

    [2] => stdClass Object
        (
            [id] => 26
            [ban_id] => 169
            [ban_url] => http://www.website.com/wp-content/uploads/2014/04/46871.jpg
        )

)

我还有一个Wordpress循环:

代码语言:javascript
运行
复制
$count = 0;
while ( have_posts() ) : the_post();
   $count++;
   $show_ad = $count%3 == 0;
   if ( $show_ad ):
      echo '<img src="..." alt="" />';
   endif;
endwhile;

如果$show_ad等于true (本例中每3个帖子),我想显示一个图像(甚至更多,取决于用户的选择)。

例如,每3个帖子就有一个不同的图片:

代码语言:javascript
运行
复制
[Wordpress POST 1]
[Wordpress POST 2]
[Wordpress POST 3]
   [Image 0]
[Wordpress POST 1]
[Wordpress POST 2]
[Wordpress POST 3]
   [Image 1]
[Wordpress POST 1]
[Wordpress POST 2]
[Wordpress POST 3]
   [Image 2]
[Wordpress POST 1]
[Wordpress POST 2]
[Wordpress POST 3]
   [Image 0]
...

或者另一个例子,每3个帖子就有两个不同的图片:

代码语言:javascript
运行
复制
[Wordpress POST 1]
[Wordpress POST 2]
[Wordpress POST 3]
   [Image 0]
   [Image 1]
[Wordpress POST 1]
[Wordpress POST 2]
[Wordpress POST 3]
   [Image 2]
   [Image 0]
[Wordpress POST 1]
[Wordpress POST 2]
[Wordpress POST 3]
   [Image 1]
   [Image 2]
[Wordpress POST 1]
[Wordpress POST 2]
[Wordpress POST 3]
   [Image 0]
   [Image 1]
...

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-25 16:02:43

在回顾了你的回答之后,我相信回答你问题的最好方法就是为你的横幅广告创建一个增量变量。

检查以下对while循环的更改。

代码语言:javascript
运行
复制
$count = 0;
$banner_count = 0;
while ( have_posts() ) : the_post();
   $count++;
   $show_ad = $count%3 == 0;
   if ( $show_ad ):
      //I dont know the name of the banner object so i gave it $banner_object
      $banner_url = $banner_object[$banner_count]->ban_url;
      echo '<img src="' .$banner_url .'" alt="" />';

      //Increment Banner
      $banner_count++;

   endif;

希望这能帮上忙!如果你还在找别的东西请告诉我。如果您只有一定数量的横幅,那么当banner_count到达横幅对象的末尾时,您可能希望重新设置它。见下面的代码

代码语言:javascript
运行
复制
$count = 0;
$banner_count = 0;
while ( have_posts() ) : the_post();
   $count++;
   $show_ad = $count%3 == 0;
   if ( $show_ad ):

      $banner_url = $banner_object[$banner_count]->ban_url;
      echo '<img src="' .$banner_url .'" alt="" />';

      //Increment Banner
      $banner_count++;

      //If reached the end of the banner count
      if($banner_count > count($banner_object)) { $banner_count = 0; }

   endif;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23293075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档