为foreach()不一致提供的参数无效

问题描述 投票:0回答:1

我对WordPress相对较新,我对附带代码的错误感到困惑。它运行正常返回计数但抛出上述警告。它不会在我的localhost上抛出错误,并且我在同一页面上运行类似的循环而没有警告:

<?php  
$typecount = 0;
$deal_name = "Wing Night";

$args = array( 'post_type' => 'dealdetails', 'posts_per_page' => -1  );
query_posts( $args );

while ( have_posts() ) : the_post();
      ?>
      <?php
        $deal_type = get_field('deal_type');
        foreach($deal_type as $x => $x_value){
        if($x_value == $deal_name){
        $typecount++;
        }
      }
    ?>
    <?php
endwhile;
echo '(' . $typecount. ')';
?>
php wordpress
1个回答
1
投票

您正在尝试将foreach用于非数组变量。 get_field()可能会返回非数组值。

这里有一些修复:

    $deal_type = get_field('deal_type');

    if(is_array($deal_type)){
       foreach($deal_type as $x => $x_value){
          if($x_value == $deal_name){
             $typecount++;
          }
       }
    }else{
       if($x_value == $deal_name){
          $typecount += 1;
       }
    }
© www.soinside.com 2019 - 2024. All rights reserved.