简体   繁体   English

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

[英]Separate an array with comma and string PHP

I want to separate an array with comma and word.我想用逗号和单词分隔一个数组。

This is the code that i make:这是我制作的代码:

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

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

My code print this:我的代码打印这个:

Authors: user1, user2, user3, user4 and user5作者:user1、user2、user3、user4 和 user5

I successfully made a code to implode the array with a comma and search for the last key and separate it with a word 'and'.我成功地编写了一个代码,用逗号对数组进行内爆,并搜索最后一个键并用单词“and”分隔。

But that's what I want but I failed after more than 2 days of work on this:但这就是我想要的,但是经过 2 天多的工作后我失败了:

Authors: user1, user2, and user3 and 2 others.作者:user1、user2、user3 和 2 个其他人。

Here's one way to do it:这是一种方法:

Start by imploding the first two array elements.首先内爆前两个数组元素。 ( array_splice will remove them from $array .) array_splice将从$array删除它们。)

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

Add the third one if it's there.如果有的话,添加第三个。 ( array_shift will remove it from $array too.) array_shift也会从$array删除它。)

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

Count the rest and add them, if any are left.计算其余的并添加它们,如果有的话。

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

While I always look for the clever calculated process for handling a task like this, I'll offer a much more pedestrian alternative.虽然我一直在寻找巧妙的计算过程来处理这样的任务,但我会提供一个更简单的替代方案。 (For the record, I hate writing a battery of if-elseif-else conditions almost as much as I hate the verbosity of a switch-case block.) For this narrow task, I am electing to abandon my favored array functions and conditionally print the values with their customized delimiters. (为了记录,我讨厌if-elseif-else条件,就像我讨厌switch-case块的冗长switch-case 。)对于这个狭窄的任务,我选择放弃我喜欢的数组函数并有条件地打印带有自定义分隔符的值。

While this solution is probably least scalable on the page, it is likely to be the easiest to comprehend (relate the code to its generated output).虽然此解决方案在页面上的可扩展性可能最低,但它可能是最容易理解的(将代码与其生成的输出相关联)。 If this is about "likes" or something, I don't really see a large demand for scalability -- but I could be wrong.如果这是关于“喜欢”之类的,我真的没有看到对可扩展性的大量需求——但我可能是错的。

Pay close attention to the 2-count case.密切注意 2 计数的情况。 My solution delimits the elements with and instead of , which seems more English/human appropriate.我的解决方案用and而不是 分隔元素,这似乎更适合英语/人类。

Code: ( 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";
}

Output:输出:

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
---

ps A more compact version of the same handling: ps 相同处理的更紧凑版本:

Code: ( 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 finally, here's an approach that "doctors up" the array and prepends and to the final element.最后,这里有一种方法可以“修复”数组and到最后一个元素。 I think anyway you spin this task, there's going to be a degree of convolution.我认为无论如何你旋转这个任务,都会有一定程度的卷积。

Code: ( 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);
}

During a CodeReview, I realized a "pop-prepend-push" technique: https://codereview.stackexchange.com/a/255554/141885在 CodeReview 期间,我实现了一种“pop-prepend-push”技术: https : //codereview.stackexchange.com/a/255554/141885

There are several ways to do it, one simple way :几种方法可以做到,一种简单的方法:

First you should get the numbers of elements in your array to see if it's more than 3 or not.首先,您应该获取数组中元素的数量,以查看它是否大于 3。

$count = count( $array) ;

Then if it's more than 3 , you can make your string:然后如果它超过 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 tutoria l如果您想了解有关 PHP 数组的更多信息,可以使用此链接,一个快速教程

Or the documentation或者文档

I suggest you to think your problem as a function that you can Unit-Test so it becomes easier to build and you can flexibilize your solution.我建议您将您的问题视为可以进行单元测试的功能,这样您就可以更轻松地构建并灵活化您的解决方案。

  • Use counters to track your array: total, first chunk, tail使用计数器来跟踪您的数组:总计、第一个块、尾部
  • Consider any special cases like 2 elements, 3 elements, etc.考虑任何特殊情况,例如 2 个元素、3 个元素等。
  • Get the last item with array_pop使用array_pop获取最后一项
  • Use array_slice to get the first chunk from the "take N" argument.使用array_slice从“take N”参数中获取第一个块。
  • Implode and concat as required to get the desired result根据需要内爆和连接以获得所需的结果

Here an example of how it could be.这是一个如何实现的示例。

<?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";

?>

Will output:将输出:

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

Working example here这里的工作示例


Alternative选择

An alternative for handling special cases and printing the last item value.处理特殊情况和打印最后一个项目值的替代方法。

<?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";

Will print:将打印:

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

Feel free to adjust to your needs.随意调整以适应您的需求。

Working code example工作代码示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM