0

我们正在寻找一个可以合并数组键和值并特别更新它的函数。

$array = array('testing1','testing2','testing3','testing4','testing5','testing6','testing7','testing8','testing9','testing10','testing11','testing12','testing13','testing14');

我们只想像这样将 10 个值与“空格”合并。

$finalarray = array('testing1 testing2 testing3 testing4 testing5 testing6 testing7 testing8 testing9 testing10', 'testing11 testing12 testing13 testing14'); 

有没有在 PHP 中做同样事情的函数?

4

2 回答 2

2

你可以array_chunk使用array_map

    $array = array('testing1','testing2','testing3','testing4','testing5','testing6','testing7','testing8','testing9','testing10','testing11','testing12','testing13','testing14');
    $final = array_chunk($array,10);    
    $final = array_map(function ($n){return implode(" ", $n);}, $final);

输出

array
  0 => string 'testing1 testing2 testing3 testing4 testing5 testing6 testing7 testing8 testing9 testing10' (length=90)
  1 => string 'testing11 testing12 testing13 testing14' (length=39)
于 2012-09-27T06:41:09.093 回答
0

我在我的脑海中没有看到任何直接的 php 函数,但你可以尝试这样的事情:

$newArray = count($array) > 0 ? array ($array[0]) : array();
for ($i=1;$i<count($array);$i++) {
    if ($i % 10 == 0) {
       $finalarray[] = $newArray;
       $newArray = array ($array[$i]);
    } else {
       $newArray[] = $array[$i];
    }
}
if ( count($newArray) > 0 ) {
    $finalarray[] = $newArray;
}
于 2012-09-27T06:45:48.447 回答