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

更多相关文章

  1. 你能得到一个调用类的变量吗?
  2. 指导我优化我的PHP代码,用数组中的空数据填充缺失值
  3. 在数组中找到键是找不到文本[重复]
  4. 为什么foreach在循环中不修改数组时要复制数组?(复制)
  5. 如何将项添加到json文件格式化数组
  6. Laravel 5 PDO绑定变量数与令牌数不匹配
  7. 从数组php获得第一个非空值。
  8. 迭代XML元素并将元素推送到数组中
  9. 学习成绩统计-【数组操作】

随机推荐

  1. 关于PHP中self关键字的用法详解
  2. php开发一个文件管理系统(附代码)
  3. 解决CentOS7中php-fpm进程数过多导致服务
  4. php中加密解密DES的正确使用姿势
  5. CentOS 下三种 PHP 拓展安装方法
  6. PHP编译参数configure配置详解
  7. PHP使用swoole实现多线程爬虫
  8. 怎么将网站的php版本信息隐藏起来
  9. php实现性能优化
  10. 关于php中变量的初始化以及赋值方式的介