簡體   English   中英

如何從 PHP 中的數組創建逗號分隔的列表?

[英]How do I create a comma-separated list from an array in PHP?

我知道如何使用 foreach 遍歷數組的項目並附加一個逗號,但是必須去掉最后一個逗號總是很痛苦的。 有沒有一種簡單的 PHP 方法可以做到這一點?

$fruit = array('apple', 'banana', 'pear', 'grape');

最終我想要

$result = "apple, banana, pear, grape"

你想為此使用內

即: $commaList = implode(', ', $fruit);


有一種方法可以在沒有尾隨的情況下附加逗號。 如果您必須同時進行一些其他操作,您會想要這樣做。 例如,也許你想引用每個水果,然后用逗號分隔它們:

$prefix = $fruitList = '';
foreach ($fruits as $fruit)
{
    $fruitList .= $prefix . '"' . $fruit . '"';
    $prefix = ', ';
}

此外,如果您只是以“正常”方式在每個項目后附加逗號(就像您之前所做的那樣),並且您需要修剪最后一個,只需執行$list = rtrim($list, ', ') . 在這種情況下,我看到很多人不必要地使用substr

這就是我一直在做的事情:

$arr = array(1,2,3,4,5,6,7,8,9);

$string = rtrim(implode(',', $arr), ',');

echo $string;

輸出:

1,2,3,4,5,6,7,8,9

現場演示:http: //ideone.com/EWK1XR

編輯:根據@josantgv 的評論,您應該能夠從上面的示例中刪除rtrim() IE:

$string = implode(',', $arr);

結果and最后:

$titleString = array('apple', 'banana', 'pear', 'grape');
$totalTitles = count($titleString);
if ($totalTitles>1) {
    $titleString = implode(', ', array_slice($titleString, 0, $totalTitles-1)) . ' and ' . end($titleString);
} else {
    $titleString = implode(', ', $titleString);
}

echo $titleString; // apple, banana, pear and grape

類似於勞埃德的答案,但適用於任何大小的數組。

$missing = array();
$missing[] = 'name';
$missing[] = 'zipcode';
$missing[] = 'phone';

if( is_array($missing) && count($missing) > 0 )
        {
            $result = '';
            $total = count($missing) - 1;
            for($i = 0; $i <= $total; $i++)
            { 
              if($i == $total && $total > 0)
                   $result .= "and ";

              $result .= $missing[$i];

              if($i < $total)
                $result .= ", ";
            }

            echo 'You need to provide your '.$result.'.';
            // Echos "You need to provide your name, zipcode, and phone."
        }
$fruit = array('apple', 'banana', 'pear', 'grape');    
$commasaprated = implode(',' , $fruit);

我更喜歡在 FOR 循環中使用 IF 語句來檢查以確保當前迭代不是數組中的最后一個值。 如果不是,請添加逗號

$fruit = array("apple", "banana", "pear", "grape");

for($i = 0; $i < count($fruit); $i++){
    echo "$fruit[$i]";
    if($i < (count($fruit) -1)){
      echo ", ";
    }
}

有時,在某些情況下,您甚至不需要 php(例如,列表項在渲染時都在它們自己的通用標記中)如果在渲染后它們是單獨的元素,您總是可以通過 css 向所有元素添加逗號,但最后一個子元素從劇本。

我在主干應用程序中經常使用它來修剪一些任意代碼:

.likers a:not(:last-child):after { content: ","; }

基本上查看元素,定位除最后一個元素之外的所有元素,並在每個項目之后添加一個逗號。 如果情況適用,這只是一種根本不必使用腳本的替代方法。

一個功能性的解決方案是這樣的:

$fruit = array('apple', 'banana', 'pear', 'grape');
$sep = ','; 

array_reduce(
    $fruits,
    function($fruitsStr, $fruit) use ($sep) {
        return (('' == $fruitsStr) ? $fruit : $fruitsStr . $sep . $fruit);
    },
    ''
);

關注這個

$teacher_id = '';

        for ($i = 0; $i < count($data['teacher_id']); $i++) {

            $teacher_id .= $data['teacher_id'][$i].',';

        }
        $teacher_id = rtrim($teacher_id, ',');
        echo $teacher_id; exit;

如果做引用的答案,你可以做

$commaList = '"'.implode( '" , " ', $fruit). '"';

以上假設水果是非空的。 如果您不想做出這樣的假設,您可以使用 if-then-else 語句或三元 (?:) 運算符。

我知道如何使用 foreach 循環遍歷數組的項目並附加一個逗號,但是必須去掉最后一個逗號總是很痛苦。 有沒有一種簡單的 PHP 方法來做到這一點?

$fruit = array('apple', 'banana', 'pear', 'grape');

最終我想要

$result = "apple, banana, pear, grape"
$letters = array("a", "b", "c", "d", "e", "f", "g"); // this array can n no. of values
$result = substr(implode(", ", $letters), 0);
echo $result

輸出-> a,b,c,d,e,f,g

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM