【问题标题】:Foreach issue with empty variables空变量的foreach问题
【发布时间】:2013-02-21 12:33:59
【问题描述】:

我想回到我原来的问题:Populating a calendar with PHP foreach code

在本地主机服务器上工作时,脚本可以工作,但是当在线上传时,日历没有出现,Chrome 给我以下错误:

<b>Warning</b>:  array_values() [<a href='function.array-values'>function.array-values</a>]: The argument should be an array in <b>/home/flyeurov/public_html/lib/skins/flyeuro/events/events_index.tpl</b> on line <b>30</b>
<b>Warning</b>:  array_merge() [<a href='function.array-merge'>function.array-merge</a>]: Argument #2 is not an array in <b>/home/flyeurov/public_html/lib/skins/flyeuro/events/events_index.tpl</b> on line <b>30</b>
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/flyeurov/public_html/lib/skins/flyeuro/events/events_index.tpl</b> on line <b>30</b><br />

我发现,当我过去没有发生任何事件 = $history 因此为空,或者为未来计划的事件 = $events 为空时,就会发生这种情况。

foreach(array_merge(array_values($history), array_values($events)) as $event)

但我的系统有时会绑定到没有计划任何事件,因此为空$event,所以我的问题是,我怎样才能绕过 foreach 以显示带有一个或另一个空变量的日历?

【问题讨论】:

  • 只需将另一个参数添加到合并中:new array()
  • 如果过去没有事件,$history 首先应该是一个空数组,而不是一个空变量。正确初始化你的变量,你会没事的。

标签: php


【解决方案1】:
if(!empty($history) || !empty($events)){
   foreach(array_merge(array_values($history), array_values($events)) as $event){...}
}

在您的情况下,这将是一个更好的解决方案(删除了 if 条件):

$history = (!empty($history))?$history:array();
$events = (!empty($events))?$events:array();
foreach(array_merge(array_values($history), array_values($events)) as $event){...}

【讨论】:

  • 日历现在消失了。
  • 你在 foreach 循环中到底在做什么?
  • pastebin.com/0f5sipJu - 结果应该是即使变量为空,日历也应该出现,但它们当前有事件,但仍然没有出现。我一定在那个代码中搞砸了。 Chrome 正在向eventdates 发送Syntax Error: unexpected token: [
【解决方案2】:

如果 (!empty($array)) { ... }

这将在 foreach 之前进行检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多