2011-06-10 53 views
0

我有3個與相同數量的項目如何將3個數組插入到2個MySql表中?

$id= array(1, 2, 3, 4, 5); 
$fruit= array('apple', 'banana', 'ananas', 'orange', 'lemon'); 
$price= array(32, 54, 26, 97, 47); 

的簡單陣列我有兩個MySQL表。第一個包含行'id'和'name'的table'fruits'以及包含行'fruit'和'price'的第二個表'prices'。

在table'fruits'中,我需要插入數組$ id和$ fruit中的項目。如果沒有具有相同ID號的行,來自$ id的項應該放入'id'行並且來自$ fruit的項應該放在行'name'中。此外,我需要將陣列$ id和$ price中的所有項插入到表'價格'中。與之前的表格相同,來自數組$ id的項目應放置在行'fruit'中,而來自數組$ price的項目應放入行'price'中。

謝謝你的幫助。

+0

請不要使用這樣的字符串('apple','banana'),這是一個非常糟糕的做法。用'蘋果','香蕉'。 – kapa 2011-06-10 13:51:04

回答

6
$id= array(1, 2, 3, 4, 5); 
$fruit= array('apple', 'banana', 'ananas', 'orange', 'lemon'); 
$price= array(32, 54, 26, 97, 47); 


foreach($fruit as $key => $fruitName) 
    { 
    $query = ' 
     INSERT INTO fruits (id, name) 
     VALUES ('.$id[$key].', '.$fruit[$key].') 
     '; 
    // execute 
    $query = ' 
     INSERT INTO prices (id, price) 
     VALUES ('.$id[$key].', '.$price[$key].') 
     '; 
    // execute 
    } 

但請不要問我在這裏驗證輸入[密鑰等的存在] - 這是快速的代碼片段,可能會有所幫助。 ;]

順便說一句。如果你有一張桌子水果(ID,名字,價格),會更好。 ]

1

使用array_combine()創建兩個新的陣列:

  • 一個與$fruit
  • 一個通過每個這兩個關聯數組與$price

環路組合$id組合$id,和插入件你的記錄。

相關問題