2017-10-16 69 views
0

我有這個數據我內爆。分解數據返回單個詞

$fruit = implode(", ",$_POST["fruit"]); 

我將這些數據存儲在一個mysql表中。該tablerow的看起來是這樣的:

ID: 1 
UserID: 5 
chosen: Apple, Banana, Orange 

我意識到這非常愚蠢的存儲這樣的數據,並比較想保存我的數據是這樣的:

ID: 1 
UserID: 5 
Fruit: Apple 

ID: 2 
UserID: 5 
Fruit: Banana 


ID: 3 
UserID: 5 
Fruit: Orange 

的問題是我有一個像theese 100記錄以這種方式存儲,並希望聽到是否有一種方式與PHP來循環出舊數據,並將其插入到一個新的表中,使它看起來像上面的例子,所以我不必改變所有記錄manualy?

+1

'implode()'的相反部分是'explode()'。使用它。 – Barmar

+0

從表中讀取每一行,使用'explode()'拆分單詞,在循環中插入新記錄,然後刪除原始記錄。 – Barmar

+0

「選擇」產品的數量是否始終相同,即3? – Moseleyi

回答

1

像這樣的東西應該做的伎倆(其中$mysqli是你的連接):

if($result = $mysqli->query("SELECT * FROM `table1`")){ // select all data from the current table (where the imploded data is) 
    if($stmt = $mysqli->prepare("INSERT INTO `table2` SET `UserID`=?, `Fruit`=?")){ // prepare insertion in the new table (I'm assuming that the ID column is autoincremented) 
     while($data = $result->fetch_array()){ // get data as an array 
      $fruits = explode(', ', $data['chosen']); // explode the fruits 
      foreach($fruits as $fruit){ // loop through the fruits 
       $stmt->bind_param('is', $data['UserID'], $fruit); // bind data 
       $stmt->execute(); // insert row 
      } 
     } 
    } 
} 

我沒有實際測試它,但你可以嘗試一下。

+0

@Hazelcraft直到今天,我仍然想知道它是否工作或什麼,哈哈。我希望你現在能夠解決這個問題! – Zeke