Php 如何将每个数组元素附加到循环中以前的数组元素

Php 如何将每个数组元素附加到循环中以前的数组元素,php,arrays,Php,Arrays,我已经尽了最大的努力,但我似乎不知道如何正确地回答这个问题 我首先将一个字符串拆分成一个数组,其中包含空格 $str = "a nice and sunny day today"; $split = explode(' ', $str); 我怎么可能得到一个如下所示的数组: $new[0] = 'a'; $new[1] = 'a nice'; $new[2] = 'a nice and'; $new[3] = 'a nice and sunny'; 而不是手动执行此操作 $new[] = $

我已经尽了最大的努力,但我似乎不知道如何正确地回答这个问题

我首先将一个字符串拆分成一个数组,其中包含空格

$str = "a nice and sunny day today";
$split = explode(' ', $str);
我怎么可能得到一个如下所示的数组:

$new[0] = 'a';
$new[1] = 'a nice';
$new[2] = 'a nice and';
$new[3] = 'a nice and sunny';
而不是手动执行此操作

$new[] = $split[0];
$new[] = $split[0] . $split[1];
$new[] = $split[0] . $split[1] . $split[2];
$new[] = $split[0] . $split[1] . $split[2] . $split[3];
你可能可以看到正在发生的模式

现在,由于这可能发生在大约15个单词上,我正试图找出一种使用foreach/某种函数来实现这一点的较短方法。有什么想法吗

$tmp = array();
$new = array();
for($i = 0; $i < count($split); $i++)
  {
    $tmp[] = $split[$i];
    $new[] = implode(' ',$tmp);
  }
这当然不是问题根据

您可以这样做:

$str = "a nice and sunny day today";
$split = explode(' ', $str);

$newList = array();
// Non-empty string?
if($str) {
    // Add the first element
    $newList[] = $split[0];
    for($i = 1; $i < count($split); $i++) {
        // New element gets appended with previous
        $newList[] = $newList[$i-1] . " " . $split[$i];
    }
}

只需在循环中构建字符串并添加到数组中

$str = "a nice and sunny day today";
$split = explode(' ', $str);
$final_array = array();

$i = 0;
$string = '';
$spacer = '';
for ($i = 0; $i < count($split); $i++) {
    $string .= $spacer . $split[$i];
    $final_array[] = $string;
    $spacer = ' ';
}
$str=“今天天气晴朗”;
$split=explode(“”,$str);
$final_array=array();
$i=0;
$string='';
$spacer='';
对于($i=0;$i
您可以使用回调函数来实现以下目的:

$result = array_filter(array_map(function($k) use($split) { 
    return implode(' ', array_slice($split, 0, $k)); 
}, array_keys($split)));

print_r(array_values($result));
输出:

Array
(
    [0] => a
    [1] => a nice
    [2] => a nice and
    [3] => a nice and sunny
    [4] => a nice and sunny day
)

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(3) "1 2"
  [2]=>
  string(5) "1 2 3"
}
$str = "a nice and sunny day today";
$split = explode(' ', $str);
$final_array = array();

$i = 0;
$string = '';
$spacer = '';
for ($i = 0; $i < count($split); $i++) {
    $string .= $spacer . $split[$i];
    $final_array[] = $string;
    $spacer = ' ';
}
$result = array_filter(array_map(function($k) use($split) { 
    return implode(' ', array_slice($split, 0, $k)); 
}, array_keys($split)));

print_r(array_values($result));
Array
(
    [0] => a
    [1] => a nice
    [2] => a nice and
    [3] => a nice and sunny
    [4] => a nice and sunny day
)