简体   繁体   中英

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:

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

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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