2017-07-29 36 views
0
$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.']; 

回答

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

如果最后一个元素是短这将无法正常工作。尝试在''巧克力'之后添加''pop'并运行你的代码 – BeetleJuice

+0

我试图实现这个代码,但没有意识到它有这个问题。不知道如何流行将被用来解决这个问题?也许一个检查,看看它的最后一个元素,如果是这样操作'继续'? – Hasen

+0

https://stackoverflow.com/a/45386399/7498878 –

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

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); 
+0

与Tejaas Patel的回答一样,如果最后一个数组元素具有'strlen <6',则此代码将失败。 – BeetleJuice

+0

我没有想到这一点。那么,正确的人应该做的工作。 –

0

更新后的代码添加后弹出巧克力。

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

相关问题