php代码无法正常工作,代码有什么问题?

时间:2017-06-25 10:16:50

标签: php wordpress foreach

我正在尝试修复一些代码,但无法找到它。 我希望你们能帮助我!

错误:

  

警告:为foreach()提供的参数无效   第148行/home//public_html/wp-content/plugins//view/import.php

<?php foreach ($product['sku_products']['attributes'] as $attr): ?>
  

警告:为foreach()提供的参数无效   第209行/home//public_html/wp-content/plugins//view/import.php

<?php foreach ($product['sku_products']['variations'] as $i => $var):
 ?>

非常感谢你。

1 个答案:

答案 0 :(得分:2)

foreach期望参数应该是数组或对象

在您的情况下,$product['sku_products']['attributes']可以是nullfalse,也可以不是array

所以你可以使用isset()is_array()

完成以下操作
if(isset($product['sku_products']['attributes']) && is_array($product['sku_products']['attributes']))
{
   foreach ($product['sku_products']['attributes'] as $attr):
}

修改您的视图,如下所示

<?php if(isset($product['sku_products']['attributes']) && is_array($product['sku_products']['attributes'])):?>
   <?php foreach ($product['sku_products']['attributes'] as $attr): ?>
          <p>Your contents goes here</p>
   <?php endforeach;?>
<?php endif;?>

以下是测试的示例

$ php -r 'foreach(null as $test){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

$ php -r 'foreach(false as $test){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

$ php -r '$p="string";foreach($p as $test){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1
相关问题