将php中的字符串数组连接成2个或更多字符串

时间:2011-06-29 09:22:44

标签: php string

我有以下代码,它接受一个字符串数组,并将其拆分为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个字符串,

这是非常简单的事情,但我无法做到。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
)