如果嵌套的foreach为空,则foreach语句回显一次?

时间:2013-11-13 21:12:52

标签: php wordpress foreach

好的我有一个foreach语句在wordpress中搜索3个多站点博客中的关键字,如下所示:

<?php
 foreach ( $blogs as $blog ):
 switch_to_blog($blog['blog_id']);
 $search = new WP_Query($query_string);  
                     if ($search->found_posts>0) {
                            foreach ( $search->posts as $post ) {
echo "POST CONTEN";
                            }
                    }elseif ($search->found_posts===0) {
                        # code...
                        $notfound = true;
                    }
        endforeach;
if ($notfound) {
    # code...
    echo "POST NOT FOUND";
}

如果在所有的博客中都没有使用关键字的帖子,那么它可以正常运行,但是如果在博客1上有帖子而在博客2或3上没有,那么它仍然会发布POST NOT NOT FOUND为什么? 克里斯 // * ** * **** 更新 * 的** * ** * ** * ** * ** * 的** * ** * ** * ** * ** * 的**** /

<?php
 $searchfor = get_search_query(); // Get the search query for display in a headline
 $query_string=esc_attr($query_string); // Escaping search queries to eliminate potential MySQL-injections
 $blogs = get_blog_list( 0,'all' );
 $notfound = true;
 foreach ( $blogs as $blog ):
 switch_to_blog($blog['blog_id']);
 $search = new WP_Query($query_string);  
                     if ($search->found_posts>0) {
                         $notfound = false;
                    }
                    if($notfound){
                        ?>
                        <div class="post">
                                <h2><?php _e('Ingen resultater'); ?></h2>
                                <p><?php _e('Beklager, vi fant ingen innlegg som samsvarer med ditt søk: ' . get_search_query()); ?></p>
                            </div>
                        <?php
                    }else{
                         foreach ( $search->posts as $post ) {
echo "content";
                            }
                    }
        endforeach;

        ?>

2 个答案:

答案 0 :(得分:1)

你的逻辑是倒退的。您应该从“未找到”条件开始,并在找到某些内容时将其更改为false:

$not_found = true;

while ...
   if ($search->found_posts != 0) {
     $not_found = false;
   }
}
if ($not_found) {
  echo 'nothing found'; // $not_found is true
} else {
  echo 'found something'; // $not_found is false
}

答案 1 :(得分:-1)

抱歉格式化。刚刚复制了你的代码。与你的行为相反,看看这里找到的变量$。

<?php
 $found = false;
 foreach ( $blogs as $blog ):
 switch_to_blog($blog['blog_id']);
 $search = new WP_Query($query_string);  
                     if ($search->found_posts>0) {
                            foreach ( $search->posts as $post ) {
echo "POST CONTEN";
                            }
                      $found = true;
                    }elseif ($search->found_posts===0) {
                        # code...
                    }
        endforeach;
if ($found == false) {
    # code...
    echo "POST NOT FOUND";
}