简体   繁体   English

PHP中同一数组的元素组合

[英]Elements combination of same array in PHP

In my project, i will have to receive a string from user (in textarea). 在我的项目中,我将必须从用户(在textarea中)接收一个字符串。 Now this string will be converted into array . 现在,此string将转换为array Now the problem is that, the character length must be minimum of 3, in the following array next element should be joined to current one if character length is less than 3. How to perform it in PHP . 现在的问题是,字符长度必须至少为3,在以下数组中,如果字符长度小于3,则下一个元素应与当前元素连接。如何在PHP执行它。

a[0]=>this a[1]=>is a[2]=>an a[3]=>example a[4]=>array.

Output should be: 输出应为:

a[0]=>this a[1]=>isan a[2]=>example a[3]=>array.

Just try with: 只需尝试:

$input  = ['this', 'is', 'an', 'example', 'array.'];
$output = [];

$part = '';
foreach ($input as $value) {
    $part .= $value;
    if (strlen($part) > 3) {
        $output[] = $part;
        $part = '';
    }
}

Output: 输出:

array (size=4)
  0 => string 'this' (length=4)
  1 => string 'isan' (length=4)
  2 => string 'example' (length=7)
  3 => string 'array.' (length=6)

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

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