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

时间:2011-02-10 20:36:50

标签: php string explode delimited

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

23,45,21,40,67,22

我需要能够以某种方式切换两个值,所以例如我知道我需要在字符串中移动45个位置,所以我最终得到:

23,21,45,40,67,22

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

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

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

3 个答案:

答案 0 :(得分:1)

我只是将它们拉成阵列并在那里与它们一起工作。再次以逗号分隔格式写出字符串,并将其重写为DB。

答案 1 :(得分: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 :(得分:0)

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

$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);