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


PHP Looping through array after shuffle() causes error

我在搅乱一个数组,然后试图循环遍历它之后,得到了以下错误。我试图随机化$tags变量中post terms的顺序。

警告:为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

有人发现那个代码有什么问题吗?非常感谢任何解释。谢谢

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

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

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

bool shuffle ( array &$array )

这是正确的:

shuffle($tags);

shuffle不返回搅乱的数组,而是将数组重新排列到位。显然,它在失败时返回布尔值true或false,但这是如何发生的还是个谜。