2012-01-24 24 views
1

在洗牌數組後,我得到以下錯誤,然後試圖通過它循環。我試圖隨機化$ tags變量中的過帳條件的順序。PHP在shuffle()後循環數組導致錯誤

警告:()提供的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 

有誰看到什麼該代碼錯誤?任何解釋非常感謝。謝謝!!!

+0

如果刪除洗牌功能會發生什麼? - 你仍然有錯誤嗎? –

+0

這個錯誤基本上告訴你,當你將它傳遞給foreach時,$ tags不是數組。你有沒有嘗試調試$標籤。結果是什麼? –

回答

3

shuffle($array)返回一個布爾值:TRUE爲FALSE。 foreach需要一個數組,而不是一個布爾值,它解釋了你的錯誤。

簡單地寫shuffle($array),不$array = shuffle($array)

+0

太棒了!這樣可行。每次我加載頁面時會隨機化數組的順序嗎? –

+0

是的,PHP自動處理。 –

0

shuffle不返回洗牌陣列,它重新安排到位數組。顯然它在失敗時返回布爾值true或false,但是如何發生這種情況是一個謎。