PHP在shuffle()之后循环遍历导致错误

时间:2012-01-24 15:34:37

标签: php wordpress loops shuffle

我在洗牌后发现了以下错误,然后尝试循环播放它。我试图从$ tags变量中随机化发布术语的顺序。

  

警告:为foreach()提供的参数无效

以下是发生错误的地方

$tags = wp_get_post_terms( $post->ID , $taxonomy, $tax_args);
$tags = shuffle($tags);
if ($tags) {
  foreach ($tags as $tag) { 
       // so on ...

和完整的功能

$backup = $post; // backup the current object
$taxonomy = 'character' ;//  e.g. post_tag, category, custom taxonomy
$param_type = 'character'; //  e.g. tag__in, category__in, but genre__in will NOT work
$post_types = get_post_types( array('public' => true), 'names' );
$tax_args=array('orderby' => 'none');
$tags = wp_get_post_terms( $post->ID , $taxonomy, $tax_args);
$tags = shuffle($tags);
if ($tags) {
  foreach ($tags as $tag) {
    $args=array(
      "$param_type" => $tag->slug,
      'post__not_in' => array($post->ID),
      'post_type' => $post_types,
      'orderby' => 'rand',
      'caller_get_posts' => 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
        <?php
      endwhile;
    }
  }
}
$post = $backup;  // copy it back
wp_reset_query(); // to use the original query again

有人看到该代码有什么问题吗?任何解释都非常感激。感谢!!!

3 个答案:

答案 0 :(得分:4)

shuffle($array)返回一个布尔值:TRUE为FALSE。 foreach需要一个数组,而不是布尔值,它可以解释你的错误。

只需撰写shuffle($array),而不是$array = shuffle($array)

答案 1 :(得分:1)

http://php.net/manual/en/function.shuffle.php

bool shuffle ( array &$array )

这是正确的:

shuffle($tags);

答案 2 :(得分:0)

shuffle不返回混洗数组,它会重新排列数组。显然它在失败时返回布尔值true或false,但是如何发生这种情况是个谜。