dongyuli4538 2011-02-10 20:36
浏览 69
已采纳

在逗号分隔的字符串中切换值的位置

I have a comma delimited string held within a database field that could contain any number of values:

23,45,21,40,67,22

I need to be able to somehow switch two values, so for example I know I need to move 45 one position down the string, so I end up with:

23,21,45,40,67,22

The reason for this is that the numbers all correspond to the IDs held in another database table, and their position in the sting determine the order those items will be printed on screen. Before you ask about database design - I've inherited it and it cannot be changed without significant work to an entire application.

So I've thought about exploding the string, identifying the position of the target number and swapping it with the one next-door, but I'm unsure of how this can be achieved when the total number of values is not known.

Any things? I suspect the solution will be cumbersome, but needs must!!

  • 写回答

3条回答 默认 最新

  • ds3464 2011-02-10 20:45
    关注

    assuming you need to only move the desired value down one position in the array:

    $values = explode(',', $data_string);
    
    $value_to_move = 45;
    
    $value_count = count($values);
    for($i=0;$i<$value_count;$i++)
    {
        if($values[$i] == $value_to_move)
        {
            if($i < ($value_count-1))
            {   // if the value to move is NOT at the end of the list already
                $values[$i] = $values[$i+1];
                $values[$i+1] = $value_to_move;
                $i++;
            }
        }
    }
    $new_data_string = implode(',', $values);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?