5

How to implode foreach() with comma?

foreach($names as $name) {
    //do something
    echo '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}

Want to add comma after each link, except the last one.

4

6 回答 6

26

Raveren's solution is efficient and beautiful, but here is another solution too (which can be useful in similar scenarios):

$elements = array();
foreach($names as $name) {
    //do something
    $elements[] = '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}
echo implode(',', $elements);
于 2010-09-02T10:59:06.593 回答
12

您需要转换数组而不是使用 foreach 进行迭代。您可以使用array_map.

带闭包的 PHP 5.3 语法

echo implode(", ", array_map(function($name) use($url, $title)
{
    return '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}, $names));

PHP 5.3 之前的兼容语法

function createLinkFromName($name)
{
    return '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}
echo implode(", ", array_map('createLinkFromName', $names));

PHP 5.3 语法具有更好的可靠性

function a_map($array, $function)
{
    return array_map($function, $array);
}

echo implode(", ", a_map($names, function($name) use($url, $title)
{
    return '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}));
于 2010-09-02T11:01:33.657 回答
3
$first = TRUE;
foreach($names as $name) {
    //do something
    if(!$first) { echo ', '; }
    $first = FALSE;
    echo '<a href="', $url, '" title="', $title, '">', $name, '</a>';
}
于 2010-09-02T11:00:24.440 回答
2
foreach($names as $name) {
    //do something
    $str .= '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>,';
}
echo substr($str,0,-1);

EDIT: as the comments point out, this way of doing things is a little error prone if you change the separator (precisely its length) and forget the substr parameter. So use the foreach method unless performance is absolutely critical.

于 2010-09-02T10:56:42.170 回答
2
$s = '';
foreach ($names as $name) {
  if ($s) $s .= ', ';
  $s .= '<a href="' . $url . '" title="' . $title . '">' . $name . '</a>';
}
于 2010-09-02T11:03:28.733 回答
1

Here is an ugly solution using echo:

 $total = (count($names) - 1 );

 foreach($names as $i => $name) 
 {
      if($i != $total) 
           echo '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>, ';
      else
           echo '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
 }
于 2010-09-02T10:58:36.847 回答