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

时间:2014-04-25 12:22:44

标签: php wordpress

我有一个对象数组:

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循环:

$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个帖子有1个不同的图片:

[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个帖子有2个不同的图像:

[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]
...

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

在审核了您的回复后,我认为回答问题的最佳方法是为横幅广告创建增量变量。

查看while循环的以下更改。

$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到达横幅对象的末尾时重置它。见下面的代码

$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;