为foreach逻辑条件提供的参数无效

时间:2016-08-30 17:01:54

标签: field

我正在为条件逻辑创建一个插件,但我有这个错误:

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\ on line 128

这是代码:

function xwtLoadVariationSettingsFields( $variations ) {
    $fields = json_decode(get_post_meta($variations[ 'variation_id' ],'xwtvarLinkData',true));
    echo '<div class="xwtVariationFields">';
    foreach($fields as $k=>$v){
        $kParts = explode("--",$k);
        $field1 = explode("__",$kParts[0]);
        $field2 = explode("__",$kParts[1]);
        $div = '<div firstID="'.$field1[0].'" firstVal="'.$field1[1].'" secondID="'.$field2[0].'" secondVal="'.$field2[1].'" value="'.$v.'"></div>';
        echo $div;
    }
    echo '</div>';
    return $variations;

}

推荐?

2 个答案:

答案 0 :(得分:0)

我会google foreachjson_decodeget_post_meta函数。在foreach中,$fields需要是一个数组。我猜是

$fields = json_decode(get_post_meta($variations[ 'variation_id' ],'xwtvarLinkData',true));

不会返回数组。

答案 1 :(得分:0)

function xwtLoadVariationSettingsFields( $variations ) {
  $fields = json_decode(get_post_meta($variations[ 'variation_id' ],'xwtvarLinkData',true));
  echo '<div class="xwtVariationFields">';
    if(is_array($fields) && !empty($fields)){
      foreach($fields as $k=>$v){
            $kParts = explode("--",$k);
            $field1 = explode("__",$kParts[0]);
            $field2 = explode("__",$kParts[1]);
            $div = '<div firstID="'.$field1[0].'" firstVal="'.$field1[1].'" secondID="'.$field2[0].'" secondVal="'.$field2[1].'" value="'.$v.'"></div>';
            echo $div;
        }
      }
    echo '</div>';
return $variations;
}