【问题标题】:PHP foreach causes "Invalid argument supplied for foreach()" [duplicate]PHP foreach 导致“foreach() 提供的参数无效”[重复]
【发布时间】:2018-08-02 07:28:38
【问题描述】:

我有一个 foreach 循环,它根据 ACF 转发器字段 (map_destinations) 的内容执行某些操作。如果有目的地,它可以正常工作,但如果没有,我会得到:

“为 foreach() 提供的参数无效”

这是我的代码:

$map_destinations = get_field('map_destinations', $tour_id);        
$map = array();
    foreach ($map_destinations as $map_destination) {
    $map[] = $map_destination['destination'];
}

我尝试了各种解决方案,但都没有奏效。最普遍接受的方法似乎是:

$map_destinations = get_field('map_destinations', $tour_id);        
$map = array();
if (is_array($map)) {
    foreach ($map_destinations as $map_destination) {
    $map[] = $map_destination['destination'];
    }
}

我哪里错了?请多多包涵,我刚刚开始掌握 php。

【问题讨论】:

  • $map_destinations 不是数组 :) 您可以使用var_dump($map_destinations) 找出它是什么
  • get_field 应该返回一个空数组,即使没有可用的数据可以轻松解决

标签: php


【解决方案1】:

您不应检查is_array($map),而应检查is_array($map_destinations)!empty()

$map_destinations = get_field('map_destinations', $tour_id);        
$map = array();
if (is_array($map_destinations)) {
    foreach ($map_destinations as $map_destination) {
        $map[] = $map_destination['destination'];
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 2012-11-13
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多