三元 foreach 嵌套在 if / else 中



我想知道如何在三元或替代语法中使用三元重写以下内容。

$tags = get_the_tags();
if (!empty($tags)) {
    foreach ($tags as $tag) {
        echo $tag->name . ', ';
    }    
} else {
    echo 'foobar';
}

没有三元foreach这样的东西。但是,您可以像这样将条件语句设置为三元

echo empty($tags) ? 'foobar' :
implode(', ',array_map(create_function('$o', 'return $o->name;'),$tags)) ;

;)

输出

福, 酒吧, 约翰

解释

我们创建一个闭包,返回所有标签的 name 属性数组,然后简单地根据需要内爆它。如果标签为空,我们显示foobar,全部在一行中。

array_reduce的解决方案:

echo (empty($tags))? 'foobar': array_reduce($tags, function($prev, $item){
    return $prev.(($prev)? ", " : "").$item->name;
}, "");
// the output:
bob, john, max

http://php.net/manual/ru/function.array-reduce.php

最新更新