php - Switch placement of values in comma delimited string -
i have comma delimited string held within database field contain number of values:
23,45,21,40,67,22
i need able somehow switch 2 values, example know need move 45 1 position down string, end with:
23,21,45,40,67,22
the reason numbers correspond ids held in database table, , position in sting determine order items printed on screen. before ask database design - i've inherited , cannot changed without significant work entire application.
so i've thought exploding string, identifying position of target number , swapping 1 next-door, i'm unsure of how can achieved when total number of values not known.
any things? suspect solution cumbersome, needs must!!
assuming need move desired value down 1 position in 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 value move not @ end of list $values[$i] = $values[$i+1]; $values[$i+1] = $value_to_move; $i++; } } } $new_data_string = implode(',', $values);
Comments
Post a Comment