从数组中构建越来越长的字符串
16lz
2021-01-22
I am writing a PHP function that will take an array in the following format:
我正在编写一个PHP函数,它将采用以下格式的数组:
array(
'one',
'two',
'three'
)
And echo the following strings:
并回应以下字符串:
one
one-two
one-two-three
I can't figure out how to do this. I've tried using a variable to store the previous one and then use it, but it only works for one:
我不知道怎么做。我尝试使用一个变量来存储前一个变量,然后使用它,但它只适用于一个:
$previous = null;
for($i = 0; $i < count($list); $i++) {
echo ($previous != null ? $route[$previous] . "-" : '') . $route[$i];
$previous = $i;
}
Outputting:
输出:
one
two
two-three
That approach would probably be inefficient anyway, as this script should technically be able to handle any length of array.
无论如何,这种方法可能是低效的,因为从技术上讲,这个脚本应该能够处理任意长度的数组。
Can anybody help?
有人能帮忙吗?
7 个解决方案
#1
6
for ($i = 1, $length = count($array); $i <= $length; $i++) {
echo join('-', array_slice($array, 0, $i)), PHP_EOL;
}
更多相关文章
- 你能得到一个调用类的变量吗?
- 指导我优化我的PHP代码,用数组中的空数据填充缺失值
- 在数组中找到键是找不到文本[重复]
- 为什么foreach在循环中不修改数组时要复制数组?(复制)
- 如何将项添加到json文件格式化数组
- Laravel 5 PDO绑定变量数与令牌数不匹配
- 从数组php获得第一个非空值。
- 迭代XML元素并将元素推送到数组中
- 学习成绩统计-【数组操作】