Switch placement of values in comma delimited string

508 views Asked by At

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

There are 3 answers

0
Patrick On BEST ANSWER

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);
1
John On

I'd just pull them into an array and work with them there. Write the string out in comma-delimited format again, and rewrite that to the DB.

0
Marc B On

Assuming you know exactly which two values to switch in that list, then explode is the best option:

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