找到foreach()循环的最后一个条目,内爆不起作用

car*_*age 4 php foreach implode

我遍历我的数组来打印文章名称:

<?php
if ($articles) { 
    foreach($articles as $article) { 
        echo $article->name.", ";       
    } // end foreach article
} // end if has articles
?>
Run Code Online (Sandbox Code Playgroud)

这显然会产生类似的东西

Apple, Banana, Mango,
Run Code Online (Sandbox Code Playgroud)

但我正在寻找:

Apple, Banana, Mango
Run Code Online (Sandbox Code Playgroud)

我尝试了一些像这样的内爆声明:

<?php
if ($articles) { 
    foreach($articles as $article) { 
        echo implode(", ", $article->name);     
    } // end foreach article
} // end if has articles
?>
Run Code Online (Sandbox Code Playgroud)

要么

<?php
if ($articles) { 
    echo implode(", ", $articles->article->name);       
} // end if has articles
?>
Run Code Online (Sandbox Code Playgroud)

这些都不适合我.怎么做对了?谢谢你的提示!

Bol*_*ock 6

您可以使用foreach将文章名称添加到数组,然后添加名称implode()数组.

<?php
if ($articles) { 
    $article_names = array();

    foreach($articles as $article) { 
        $article_names[] = $article->name;
    } // end foreach article

    echo implode(', ', $article_names);
} // end if has articles
?>
Run Code Online (Sandbox Code Playgroud)


oez*_*ezi 6

检查你的第一个循环迭代,在文本之前使用逗号并在第一次迭代时保留这个逗号是非常容易的:

<?php
if ($articles) { 
    $firstiteration = true:
    foreach($articles as $article) { 
        if(!$firstiteration){
            echo ", ";
        }
        $firstiteration = false;
        echo $article->name;       
    } // end foreach article
} // end if has articles
?>
Run Code Online (Sandbox Code Playgroud)

另一个(在我的选择中更漂亮)可能是覆盖你的文章类的_toSting() - 方法:

...
function __toString(){
    return $this->name;
}
...
Run Code Online (Sandbox Code Playgroud)

简单地说 echo implode(", ",$articles)