dousou1878 2014-08-22 13:42
浏览 32
已采纳

将List组件转换为list

Is there an easy way to expand out a list to individual components? E.g. if a client requests the following lines: 1,5,6,10-15,20,21 is there an easy way using PHP (or MySQL directly) to convert this to a list of: 1,5,6,10,11,12,13,14,15,20,21.

I am thinking I can move each element into an array and then look for the '-' character in an 'a-b' component and use that to run a loop process to add numbers from 'a' through to 'b' but there may be an easier way.

  • 写回答

1条回答 默认 最新

  • ds0409 2014-08-22 13:49
    关注

    Your process is correct and very understandable, and there seems to be no built-in function to do it. Using the range function makes it easier than with a regular for loop.

    $values = explode (',', $str);
    
    foreach ($values as $val) {
      if (strpos($val, '-') !== false) {
        $range_values = explode ('-', $val);
        foreach (range($range_values[0], $range_values[1]) as $val_to_add) {
          $values[] = $val_to_add;
        }
      }
    }
    
    sort($values);
    
    $str = implode (',', $values);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计