【问题标题】:having problems with php syntax and foreachphp语法和foreach有问题
【发布时间】:2009-11-12 07:28:51
【问题描述】:

收到警告:第 41 行 /home/maxer/domains/x/public_html/x/items.php 中为 foreach() 提供的参数无效

第 41 行是 foreach

$items = getUserList($user,0,100);

foreach($items as $item){

    echo "<img src=\"".$item['image']."\">"; //image
    echo ""; //title
    echo ""; //button for add to list

}

【问题讨论】:

  • vardump($items) 说什么?
  • 顺便说一句,在编写一个可能返回数组的函数时,最好做的一件事是,如果没有找到任何项,则让它返回一个空数组。这样,您就永远不会遇到此错误。
  • 我切换到这种方法以及投射

标签: php


【解决方案1】:

这意味着$items 不是数组或者没有实现 Traversable。如果您向foreach 提供了不是数组并且没有实现 Traversable 的东西,它会抱怨此消息。要么将getUserList 的结果转换为一个数组,要么检查它是否为一个。

$items = (array)getUserList($user,0,100);

或类似的东西:

$items = getUserList($user,0,100);

if (!is_array($items)) {
    // error
} else {
    foreach ($items …) {
        // …
    }
}

【讨论】:

  • 为了迂腐,数组实现 Traversable 的任何值都可以在 foreach 循环中使用。
【解决方案2】:

您的函数 getUserList 不返回数组 确保 $items 是这样写的数组:

$items = (array) getUserList($user,0,100);

【讨论】:

  • 在找到解决方案后人们忘记了这个网站直到下一期)
猜你喜欢
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2017-04-21
  • 2011-09-21
相关资源
最近更新 更多