用逗号和字符串分隔数组 PHP

Separate an array with comma and string PHP

我想用逗号和单词分隔数组。

这是我编写的代码:

$array = array( 'user1', 'user2', 'user3', 'user4', 'user5' );
$last = array_pop( $array );
$string = count( $array ) ? implode( ", ", $array ) . " and " . $last : $last;

printf( 'Authors: %s', $string );

我的代码打印这个:

作者:user1、user2、user3、user4 和 user5

我成功地编写了一个代码,用逗号内爆数组并搜索最后一个键并用单词分隔它 'and'。

但这就是我想要的,但经过 2 天多的工作后我失败了:

作者:user1、user2、user3 和另外 2 人。

几种方法,一种简单的方法:

首先你应该得到数组中元素的数量,看看它是否大于 3。

$count = count( $array) ;

那么如果大于 3 ,你可以使你的字符串:

if($count>3){
    $string= $array[0] . 'and' . $array[1] . 'and' . $array[2] . 'and' . ($count - 3) . "others";
}else{
    $last = array_pop( $array );
    $string = count( $array ) ? implode( ", ", $array ) . " and " . $last : $last;
    //I used exactly your code , you have several ways to do it
    //Attention ... This code may not work when your array has only one element
}
printf( 'Authors: %s', $string );

If you want to know more about PHP arrays you can use this link , a quick tutorial

Or the documentation

这是一种方法:

首先内爆前两个数组元素。 (array_splice 将从 $array 中删除它们。)

$string = implode(', ', array_splice($array, 0, 2));

如果有第三个,请添加。 (array_shift 也会将其从 $array 中删除。)

if ($array) {
    $string .= ', and ' . array_shift($array);
}

数一数剩下的,如果还剩的话,把它们加起来。

if ($n = count($array)) {
    $string .= " and $n other". ($n > 1 ? 's' : '');
    //                           conditional pluralization
}

我建议您将您的问题视为一个可以进行单元测试的函数,这样构建起来会更容易,并且您可以使您的解决方案更加灵活。

  • 使用计数器跟踪您的数组:总数、第一个块、尾部
  • 考虑任何特殊情况,例如 2 个元素、3 个元素等
  • 获取最后一项array_pop
  • 使用 array_slice 从 "take N" 参数中获取第一个块。
  • 根据需要进行内爆和连接以获得所需的结果

这是一个例子。

<?php

function niceAuthorsPrint(array $authors, $takeCount){

  $totalAuthors = count( $authors );
  $tailCount = $totalAuthors - $takeCount;

  $first = array_slice($authors, 0, $takeCount);

  $othersLabel = $tailCount == 1 ? 'other' : 'others';

  $string = implode( ", ", $first );

  if($tailCount > 0){
     $string .= " and " . $tailCount . ' ' . $othersLabel;      
  }

  return $string;
}

// take 3
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 3) ."\n";

// take 4
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 4) ."\n";

// take 5
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 5) ."\n";

?>

将输出:

user1, user2, user3 and 2 others
user1, user2, user3, user4 and 1 other
user1, user2, user3, user4, user5

Working example here


备选

处理特殊情况和打印最后一项值的替代方法。

<?php

// array of authors, number of authors to take first
function niceAuthorsPrint(array $authors, $takeCount){

  $totalAuthors = count( $authors );

  if($totalAuthors >= 3 && $takeCount >= $totalAuthors)
  {
      $takeCount = 2;
  }

  if($totalAuthors == 2 && $takeCount >= $totalAuthors)
  {
      $takeCount = 1;
  }

  $last = array_pop($authors);

  $tailCount = $totalAuthors - $takeCount;

  $first = array_slice($authors, 0, $takeCount);

  $othersLabel = $tailCount == 1 ? $last : $tailCount . ' others';

  $string = implode( ", ", $first );

  if($tailCount > 0){
     $string .= " and " . $othersLabel;      
  }

  return $string;
}

// take 3
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 3) ."\n";

// take 4
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 4) ."\n";

// take 5
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 5) ."\n";

// take original count, take first three as default
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 5) ."\n";

// take original count, take first three as default
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3'), 3) ."\n";

// take original count, take first three as default
echo niceAuthorsPrint(array( 'user1', 'user2'), 2) ."\n";

将打印:

user1, user2, user3 and 2 others
user1, user2, user3, user4 and user5
user1, user2 and 3 others
user1, user2 and 3 others
user1, user2 and user3
user1 and user2

随时根据您的需要进行调整。

Working code example

虽然我一直在寻找巧妙的计算过程来处理这样的任务,但我会提供一个更简单的替代方案。 (郑重声明,我 讨厌 编写一连串 if-elseif-else 条件几乎和我讨厌 switch-case 块的冗长一样多。)对于这个狭窄的任务,我选择放弃我最喜欢的数组函数,并有条件地打印带有自定义分隔符的值。

虽然此解决方案在页面上的可扩展性可能最低,但它可能是最容易理解的(将代码与其生成的输出相关联)。如果这是关于“喜欢”之类的,我并没有真正看到对可伸缩性的巨大需求——但我可能是错的。

密切关注 2 计数的情况。我的解决方案用 and 而不是 , 来分隔元素,这似乎更 English/human 合适。

代码:(Demo)

$arrays[] = array();
$arrays[] = array('user1');
$arrays[] = array('user1', 'user2');
$arrays[] = array('user1', 'user2', 'user3');
$arrays[] = array('user1', 'user2', 'user3', 'user4');
$arrays[] = array('user1', 'user2', 'user3', 'user4', 'user5');

foreach ($arrays as $i => $array) {
    echo "TEST $i: ";
    if (!$count = sizeof($array)) {
        echo "nobody";
    } elseif ($count == 1) {
        echo $array[0];
    } elseif ($count == 2) {
        echo "{$array[0]} and {$array[1]}";
    } elseif ($count == 3) {
        echo "{$array[0]}, {$array[1]}, and {$array[2]}";
    } else {
        echo "{$array[0]}, {$array[1]}, {$array[2]}, and " , $count - 3, " other" , ($count != 4 ? 's' : '');
    }
    echo "\n---\n";
}

输出:

TEST 0: nobody
---
TEST 1: user1
---
TEST 2: user1 and user2
---
TEST 3: user1, user2, and user3
---
TEST 4: user1, user2, user3, and 1 other
---
TEST 5: user1, user2, user3, and 2 others
---

p.s。相同处理的更紧凑版本:

代码:(Demo)

if (!$count = sizeof($array)) {
    echo "nobody";
} elseif ($count < 3) {
    echo implode(' and ', $array);
} else{
    echo "{$array[0]}, {$array[1]}";
    if ($count == 3) {
        echo ", and {$array[2]}";
    } else {
        echo ", {$array[2]}, and " , $count - 3, " other" , ($count != 4 ? 's' : '');
    }
}

最后,这里有一种方法可以“整理”数组并将 and 添加到最后一个元素。我想无论如何你旋转这个任务,会有一定程度的卷积。

代码:(Demo)

$count = sizeof($array);
if ($count < 3) {
    echo implode(' and ', $array);
} else {
    if ($count == 3) {
        $array[2] = "and {$array[2]}";
    } else {
        $more = $count - 3;
        array_splice($array, 3, $more, ["and $more other" . ($more > 1 ? 's' : '')]);
    }
    echo implode(', ', $array);
}

在一次CodeReview中,我实现了一个“pop-prepend-push”技术:https://codereview.stackexchange.com/a/255554/141885


从PHP8开始,match()也可以。实现可能如下所示:(Demo)

$count = count($array);
echo match ($count) {
         0 => 'nobody',
         1 => $array[0],
         2 => implode(' and ', $array),
         3 => "{$array[0]}, {$array[1]}, and {$array[2]}",
         default => "{$array[0]}, {$array[1]}, {$array[2]}, and " . $count - 3 . " other" . ($count != 4 ? 's' : '')
     };