我有一个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。
答案 0 :(得分:2)
您不应该检查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'];
}
}