PHP如何在保持顺序的同时将数组元素与下一个合并?

时间:2017-07-29 06:15:02

标签: php arrays preg-match implode

$array = ['coke.','fanta.','chocolate.'];

foreach ($array as $key => $value) {
  if (strlen($value)<6) {
      $new[] =  $value." ".$array[$key+1];
  } else {
      $new[] = $value;
  }
}

此代码没有达到预期的效果,实际上根本不起作用。我想要做的是,如果数组元素的字符串长度小于5,则将其与下一个元素连接。所以在这种情况下,数组应该变为:

$array = ['coke. fanta.','chocolate.'];

5 个答案:

答案 0 :(得分:2)

$array = ['coke.','fanta.','chocolate.', 'candy'];
$new = [];

reset($array); // ensure internal pointer is at start
do{
    $val = current($array); // capture current value
    if(strlen($val)>=6):
        $new[] = $val; // long string; add to $new

    // short string. Concatenate with next value
    // (note this moves array pointer forward)
    else:
        $nextVal = next($array) ? : '';
        $new[] = trim($val . ' ' . $nextVal);
    endif;

}while(next($array));

print_r($new); // what you want

Live demo

答案 1 :(得分:1)

使用array_reduce

$array = ['coke.', 'fanta.', 'chocolate.', 'a.', 'b.', 'c.', 'd.'];

$result = array_reduce($array, function($c, $i) {
    if ( strlen(end($c)) < 6 )
        $c[key($c)] .= empty(current($c)) ? $i : " $i";
    else
        $c[] = $i;
    return $c;
}, ['']);


print_r($result);

demo

答案 2 :(得分:0)

reddit.service.ts

答案 3 :(得分:0)

您需要跳过已添加的值的迭代。

$array = ['coke.', 'fanta.', 'chocolate.'];
$cont = false;

foreach ($array as $key => $value) {
    if ($cont) {
        $cont = false;
        continue;
    }

    if (strlen($value) < 6 && isset($array[$key+1])) {
        $new[] = $value.' '.$array[$key+1];
        $cont = true;
    }
    else {
        $new[] = $value;
    }
}
print_r($new);

答案 4 :(得分:0)

在巧克力后添加pop后更新了代码。

<pre>
$array = ['coke.','fanta.','chocolate.','pop'];
print_r($array);
echo "<br>";
$next_merge = "";
foreach ($array as $key => $value) {
    if($next_merge == $value){
        continue;
    }
    if (strlen($value)<6 && !empty($array[$key+1])) {
        $new[] =  $value." ".$array[$key+1];
        $next_merge = $array[$key+1];
    } else {
        $new[] = $value;
    }
}
print_r($new);
<pre>