简体   繁体   English

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

[英]concating an array of strings in php to 2 or more strings

I have the following code, which takes an array of strings, and splits it to 2 strings:我有以下代码,它接受一个字符串数组,并将其拆分为 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--;
}

Right now on a 5 index array I get to split it 3-2, I want to make it 2-3, so on text1, i'll only concate 2 string,现在在一个 5 索引数组上,我将其拆分为 3-2,我想将其拆分为 2-3,所以在 text1 上,我只会连接 2 个字符串,

This is prolly quite simple thing to do, but I'm not able to.这是很简单的事情,但我做不到。

How about this?这个怎么样?

<?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";
?>

Check this out: http://php.net/manual/en/function.array-chunk.php看看这个: http://php.net/manual/en/function.array-chunk.php

I hope I read your question correctly:我希望我正确阅读了您的问题:

$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);

Output: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM