2011-06-29 15 views
0

的陣列我有以下代碼,這需要一個字符串數組,並將其拆分爲2個字符串:concating在PHP字符串2個或多個串

$key2 = $count = count($textArray); 
$key = 0; 
while ($key2 >= $count/2){ 
    $this -> text1 = $this-> text1 . $textArray[$key]; 
    $this -> text2 = $textArray[$key2] . $this-> text2; 
    $key++; 
    $key2--; 
} 

眼下5索引陣列上我得到分裂它3-2,我想做2-3,所以對text1,我只會連續2字符串,

這是prolly很簡單的事情要做,但我不能。

回答

0

我希望我正確地讀你的問題:

$strings = array('a', 'b', 'c', 'd', 'f'); 

$new = array_map(function ($arr) { 
    return implode('', $arr); 
}, array(array_splice($strings, 0, floor(sizeof($strings)/2)), $strings)); 

print_r($new); 

輸出:

Array 
(
    [0] => ab 
    [1] => cdf 
) 
0

這個怎麼樣?

<?php 
$arr = array("qwe","rty","asd","zxc","fgh","xxx","abvah"); 

$arrNew = array_chunk($arr,ceil(count($arr)/2.0)); 
$text1 = ""; 
$text2 = ""; 

/*foreach ($arrNew[0] as $arr1){ 
    $text1 .= $arr1; 
} 
foreach ($arrNew[1] as $arr2){ 
    $text2 .= $arr2; 
}*/ 
array_map(function($x) use($text1){$text1 .= $x;},$arrNew[0]); 
array_map(function($x) use($text2){$text2 .= $x;},$arrNew[1]); 

print "$text1\n$text2\n"; 
?> 

檢查了這一點:http://php.net/manual/en/function.array-chunk.php

+2

不要使用'global'。相反,你可以寫你的匿名函數爲:'function($ x)use($ text1){$ text1。= $ x;}'。 – Yoshi

+0

@Yoshi:謝謝! :-) ..我真的不知道'使用(..)'。 – SuperSaiyan