簡體   English   中英

將 php 中的字符串數組連接到 2 個或更多字符串

[英]concating an array of strings in php to 2 or more 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--;
}

現在在一個 5 索引數組上,我將其拆分為 3-2,我想將其拆分為 2-3,所以在 text1 上,我只會連接 2 個字符串,

這是很簡單的事情,但我做不到。

這個怎么樣?

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

我希望我正確閱讀了您的問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM