在php中删除foreach中的最后一个尾随分隔符

时间:2016-11-14 08:16:40

标签: php

使用php进行foreach循环并使用/分隔下一个项目希望在最后一项中删除/

这是代码:

<?php
            $contacts = TblContact::find()->orderBy("id")->all();
            foreach ($contacts as $contact){
                echo $contact->contact."/";   //...  this has the separator /
            }
            ?>

目前它生成:

2362/2332/3332/

我希望它能够生成

2362/2332/3332    ... this has no trailing /

2 个答案:

答案 0 :(得分:1)

<?php
    $contacts = TblContact::find()->orderBy("id")->all();
    $contactList = [];
     foreach ($contacts as $contact){
        $contactList[] = $contact->contact;
     }
    echo implode("/", $contactList)
?>

试试这个

答案 1 :(得分:1)

你可以使用pluck和implode:

$contacts = TblContact::find()->orderBy("id")->pluck('contact')->all();

echo implode('/', $contacts);