php foreach显示旧段

时间:2016-01-11 17:11:06

标签: php foreach

我创建了一个脚本,其中段落中的每个其他单词都是绿色的,这是正确的。但是有一个问题,因为我使用的原始段落出现在新段落的上方,我不想要。

这个解决方案可能很简单,但我无法理解它。

有人能指出我正确的方向吗?

代码:

    <?php
$storyOfTheDay= "Once upon a time there was an old woman who loved baking gingerbread. She would bake gingerbread cookies, cakes, houses and gingerbread people, all decorated with chocolate and peppermint, caramel candies and colored frosting.

She lived with her husband on a farm at the edge of town. The sweet spicy smell of gingerbread brought children skipping and running to see what would be offered that day.

Unfortunately the children gobbled up the treats so fast that the old woman had a hard time keeping her supply of flour and spices to continue making the batches of gingerbread. Sometimes she suspected little hands of having reached through her kitchen window because gingerbread pieces and cookies would disappear.";

$storyOfTheDay = preg_split("/\s+/", $storyOfTheDay);

//Adding <span> to odd array index items
foreach (array_chunk($storyOfTheDay , 2) as $chunk) {
$storyOfTheDay[] = $chunk[0];
    if(!empty( $chunk[1]))
    {
       $storyOfTheDay[] = $chunk[1]= "<span style='color:green'>". $chunk[1] ."</span>";

    }
}


$storyOfTheDay = join(" ", $storyOfTheDay);

echo $storyOfTheDay;

输出:

Image of Output

1 个答案:

答案 0 :(得分:0)

您正在不断填充相同的数组($storyOfTheDay)。制作新的:

$storyOfTheDay = preg_split("/\s+/", $storyOfTheDay);

$newStoryOfTheDay = [];
//Adding <span> to odd array index items
foreach (array_chunk($storyOfTheDay , 2) as $chunk) {
    $newStoryOfTheDay[] = $chunk[0];
    if( !empty($chunk[1]) ){
       $newStoryOfTheDay[] = "<span style='color:green'>". $chunk[1] ."</span>";
    }
}

$newStoryOfTheDay = join(" ", $newStoryOfTheDay);
echo $newStoryOfTheDay;