如何用PHP的for循环实现指定星号替换文本序列图案?
PHP实现指定星号替换图案的正确写法
你需要生成的目标图案如下:
* two tree four five one * tree four five one two * four five one two tree * five one two tree four * * * tree four five one * * four five one two * * five one two tree * * * * * four five one * * * five one two * * * * * * * five one * * * * * * * * *
你参考的JavaScript逻辑没问题,但PHP语法和JS差异很大,你写的代码误用了JS的方法调用方式(比如$temp.slice()),下面是修正后的PHP实现:
<?php $temp = ["one", "two", "three", "four", "five"]; $arrayResult = []; $tempLength = count($temp); // 提前计算数组长度,避免循环内重复计算 for ($i = 0; $i < $tempLength; $i++) { $innerLoopCount = $tempLength - $i; for ($j = 0; $j < $innerLoopCount; $j++) { // 复制原数组(一维数组直接赋值即可,多维数组需用array_slice深拷贝) $tempArr = $temp; // 生成对应数量的星号数组 $stars = array_fill(0, $i + 1, '*'); // 用array_splice替换元素,PHP 5.6+支持用...展开数组作为参数 array_splice($tempArr, $j, $i + 1, ...$stars); $arrayResult[] = $tempArr; } } // 遍历输出结果,按目标格式添加空行 foreach ($arrayResult as $index => $line) { echo implode(' ', $line) . PHP_EOL; // 在每组结束后添加空行(对应5、9、12、14索引后) if (in_array($index, [4, 8, 11, 13])) { echo PHP_EOL; } } ?>
关键改动说明:
- 数组复制:PHP一维数组直接赋值即可完成浅拷贝,不需要像JS那样用
slice() - 生成重复元素:用PHP内置函数
array_fill()替代JS的Array().fill(),参数为「起始索引、元素数量、填充值」 - array_splice用法:PHP的
array_splice是全局函数,而非数组方法,且支持用...运算符展开数组作为插入元素(PHP 5.6及以上版本支持) - 性能优化:提前计算数组长度,避免在循环中重复调用
count()
运行这段代码就能得到你想要的图案。
内容的提问来源于stack exchange,提问作者Propig
相关产品推荐
相关产品推荐

