1

假设我有一个数组。

$shopping_list = array('eggs', 'butter', 'milk', 'cereal');

将其显示为逗号分隔列表并将单词(连词、介词等)添加到最后一个值的最简单和/或最聪明的方法是什么?期望的结果包括:

'eggs, butter, milk, and cereal'
'eggs, butter, milk, or cereal'
'eggs, butter, milk, with cereal'
'eggs, butter, milk, in cereal'
// etc.

该数组将是可变长度的,可能是关联的,最好不要修改它。它也不需要内爆;我认为这只是做这种事情的标准方式。数组取消引用也很好,但与 PHP 5.3 兼容的东西会很棒。

我在想一些事情

$extra_word = 'and';

implode(', ', array_slice($shopping_list, 0, count($shopping_list) - 1)) 
    . ', ' . $extra_word . ' '
    . implode(',', array_slice($shopping_list, count($shopping_list) - 1));

但这太糟糕了。循环更干净,并且不那么无能:

$i = 0;
$output = '';

foreach ($shopping_list as $item) {
   $i += 1;
   if ($i > 1) {
       $output .= ', ';
       if ($i === count($shopping_list)) {
           $output .= $extra_word . ' ';
       }
   }

   $output .= $item;
}

这两种方式似乎都是迂回的。有没有更好的出路?

4

3 回答 3

6

这也更干净。

$pop = array_pop($shopping_list);
echo implode(", ", $shopping_list)." and $pop.";
于 2013-05-09T10:40:09.627 回答
3

一些想法可能是复制数组。

 $array = array_values($shopping_list);
 $array[count($array)-1] = $extraword . ' ' . $array[count($array)-1];
 // implode etc.

Starx 解决方案更好。

于 2013-05-09T10:42:45.137 回答
0

另一种解决方案:

$last = count($shopping_list)-1 ;
$shopping_list[$last] = "in {$shopping_list[$last]} ;
于 2013-05-09T10:42:46.793 回答