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


How to append every array element to the previous array elements inside of a loop

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

因此,我开始将一个字符串拆分为一个数组,其中出现空格。

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

较短代码,顺序相反:

$new = array();
for($i = count($split); $i >= 0; $i--)
  {
    $new[] = implode(' ',$split);
    array_pop($split);
  }

根据array_reverse()

,这当然不是问题

您可以这样做:

$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];
    }
}

这比每次执行implode更有效,因为我们只连接当前和上一个字符串。

不过,还有一点效率低下——我们每次都在呼叫count。我们不要那样做。

$newList[] = $split[0]
for($i = 1, $len = count($split); $i < $len; $i++) {
    // New element gets appended with previous
    $newList[] = $newList[$i-1] . " " . $split[$i];
}
<?php
$str = "1 2 3";
$split = explode(' ', $str);
/* 
now $split is array('1','2','3')
Need to convert it to: array('1','1 2','1 2 3')
*/
$n = count($split);
$output = array();
for ($i = 0; $i < $n; ++$i)
{
    $output[$i] = "";
    for ($j = 0; $j <= $i; ++$j)
    {
        $output[$i] .= $split[$j];
        if ($j != $i)
        {
            $output[$i] .= " ";
        }
    }
}
var_dump($output);

输出:

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 = ' ';
}

您可以使用带有回调函数的array_map()来实现这一点:

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

演示