【问题标题】:Switch placement of values in comma delimited string在逗号分隔的字符串中切换值的位置
【发布时间】:2011-06-25 03:27:34
【问题描述】:

我在一个数据库字段中保存了一个逗号分隔的字符串,它可以包含任意数量的值:

23,45,21,40,67,22

我需要能够以某种方式切换两个值,例如,我知道我需要将 45 向下移动一个位置,所以我最终得到:

23,21,45,40,67,22

原因是这些数字都对应于另一个数据库表中保存的 ID,它们在字符串中的位置决定了这些项目将在屏幕上打印的顺序。在您询问数据库设计之前 - 我已经继承了它,如果不对整个应用程序进行大量工作就无法更改它。

所以我考虑过爆炸字符串,识别目标数字的位置并将其与隔壁的一个交换,但我不确定当值的总数未知时如何实现.

有什么吗?我怀疑解决方案会很麻烦,但需要必须!!

【问题讨论】:

    标签: php string explode delimited


    【解决方案1】:

    假设您只需将所需值在数组中向下移动一个位置:

    $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】:

      假设您确切知道要在该列表中切换哪两个值,那么 explode 是最好的选择:

      $array = explode(',', $string)
      
      # find the two values (NOTE: *NO* error handling, what if the values aren't there?)
      $index1 = array_search($first_value, $array);
      $index2 = array_search($second_value, $array);
      
      # swap them
      $temp = $array[$index1];
      $array[$index1] = $array[$index2];
      $array[$index2] = $temp;
      
      # rebuild the array
      $string = implode(',', $array);
      

      【讨论】:

        【解决方案3】:

        我只是将它们拉入一个数组并在那里与它们一起工作。再次以逗号分隔的格式写出字符串,并将其重写到 DB。

        【讨论】:

        • +1 我正要输入相同的,使用数组使工作更容易
        猜你喜欢
        • 2017-07-22
        • 1970-01-01
        • 2016-02-08
        • 1970-01-01
        • 2011-12-23
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多