Php 动态更改关联数组中的值
我想在foreach循环Php 动态更改关联数组中的值,php,Php,我想在foreach循环的最后一次迭代中动态替换一些键的值,即从[color]=>“grey”到[color]=>“green” 这是实际的脚本 <?php $line = "After six months, participants in both vitamin D supplementation groups had lost more weight and had greater reductions in their waistlines than those who hadn
的最后一次迭代中动态替换一些键的值,即从[color]=>“grey”到[color]=>“green”
这是实际的脚本
<?php
$line = "After six months, participants in both vitamin D supplementation groups had lost more weight and had greater reductions in their waistlines than those who hadn't taken the supplements, Vigna's team said";
// $chunks = str_split($line, 35);
$array = explode("\n", wordwrap($line, 40, "\n"));
// echo '<pre>' . print_r($chunks, true);
function splitTextString($array)
{
foreach($array as $key=>$value)
{
$linesArr{$key}['name'] = $value;
$linesArr{$key}['font-size'] = 27;
$linesArr{$key}['color'] = "grey";
}
return $linesArr;
}
echo "<pre>";
print_r(splitTextString($array));
echo "</pre>";
?>
只需在上一次迭代中更改字符串即可
现在问题出在哪里?希望在最后一次迭代中将颜色值,即“灰色”更改为“绿色”。end()
通过引用获取数组并将数组指针设置为最后一个元素。我希望在foreach循环之前对数组进行更多的count()
检查,然后用键检查它是否是最后一个元素。@Rizier123好的,找到了。@Rizier123-我可以将它更改为缓存最后一个键,并改为检查唯一键,如果这样做让您更高兴的话?还应避免数组中存在重复值的问题
<?php
$line = "After six months ...";
$array = explode("\n", wordwrap($line, 40, "\n"));
function splitTextString($array) {
end($array);
$last = key($array);
reset($array);
foreach($array as $key=>$value) {
$color = $key === $last ? "green" : "grey";
$linesArr{$key}['name'] = $value;
$linesArr{$key}['font-size'] = 27;
$linesArr{$key}['color'] = $color;
}
return $linesArr;
}
echo "<pre>";
print_r(splitTextString($array));
echo "</pre>";
?>