2011-02-10 104 views
2

我有一個數據庫字段內保存的逗號分隔的字符串,可以包含任意數量的值:開關放置

23,45,21,40,67,22 

我需要能夠以某種方式切換兩個值,所以對於例如,我知道我需要移動45一個位置上下串,所以我結束了:

23,21,45,40,67,22 

這樣做的原因是,這些數字都對應於另一個數據庫表中保存的ID,以及它們在位置刺痛決定了這些項目將在屏幕上打印的順序。在問你關於數據庫設計的問題之前 - 我已經繼承了它,如果沒有對整個應用程序進行重要的工作,它就不能改變。

所以我想過爆炸的字符串,確定目標號碼的位置,並與隔壁的一個交換,但我不確定如何實現這一點,當值的總數不是衆所周知。

任何事情?我懷疑這個解決方案會很麻煩,但是需要一定要!

回答

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); 
+0

這是我現在使用的代碼的基礎 - 謝謝! – Paul 2011-02-11 09:48:09

1

我只是拉他們到一個數組中,並與他們在那裏工作。再次以逗號分隔格式寫出字符串,並將其重寫到數據庫。

+0

+1我正要鍵入相同的,使用數組,使工作更容易 – Jakub 2011-02-10 20:41:10

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