【问题标题】:Invalid argument supplied for foreach Error为 foreach 错误提供的参数无效
【发布时间】:2016-10-21 10:14:56
【问题描述】:

我经常处理可以是数组或空变量的数据,并用这些数据提供一些foreach

// TV shows categories
$tvcats = get_the_terms($post->ID, 'tvshows_cat');
foreach($tvcats as $tvcat) $tvcats_arr[] = $tvcat->name;
if (count($tvcats_arr) > 1) $tvcats_str = $tvcats_arr[0] . '<br />' .  $tvcats_arr[1]; // return first 2 terms
elseif (count($tvcats_arr) == 1) $tvcats_str = $tvcats_arr[0]; // return one term
else $tvcats_str = '';

if (!empty($tvcats_str)){   
echo $tvcats_str;   
} 

tvshows_cat 是一个自定义分类法,它的工作方式类似于类别,(我的意思是它是第二个类别列表)。

在这段代码中,我想将术语限制为 2。它有效,但出现错误。

那我该如何解决呢?

【问题讨论】:

  • 因为你的$tvcats是空的
  • tvcats中有数据怎么用?

标签: php wordpress foreach


【解决方案1】:

你可以试试这样的:

$tvcats = get_the_terms($post->ID, 'tvshows_cat');
if (isset($tvcats) && !is_wp_error($tvcats)) {
    foreach($tvcats as $tvcat) {
       $tvcats_arr[] = $tvcat->name;
       if (count($tvcats_arr) > 1) $tvcats_str = $tvcats_arr[0] . '<br />' . $tvcats_arr[1]; // return first 2 terms
       elseif (count($tvcats_arr) == 1) 
           $tvcats_str = $tvcats_arr[0]; // return one term
       else 
           $tvcats_str = '';
    }
}

【讨论】:

    猜你喜欢
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多