2017-07-29 34 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

相關問題