2014-10-18 98 views
0

我有一個數組(下面),我需要執行多個MySQL插入。PHP對陣列鍵值執行foreach

KEY是需要插入的值,VALUE是需要插入的次數。

例如,在第一次迭代中,我希望插入「1」十二次。在第二次迭代中,我希望插入「2」二十八次。

Array ([1] => 12 [2] => 28 [3] => 21 [4] => 9 [5] => 0) 

現在,我知道這是最好使用一個查詢插入多行,而不是單獨的INSERT查詢,所以我希望我下面的代碼反映了這一點。我的問題是:我如何迭代關鍵值VALUE而不是單個鍵(儘管我需要遍歷鍵)。

$insert = array(); 
foreach ($ret AS $key => $item)     // $ret is the array above 
{ 
    $insert[] = "('". mysql_real_escape_string($item) . "'," . $key . "')"; 
    // This insert query should repeat only as many times as each array value 
} 

echo "INSERT INTO table (id, key) VALUES " . implode(',', $insert); 
+0

可能重複foreach循環鍵值](http://stackoverflow.com/questions/1834703/php-foreach-loop-key-value) – 2014-10-18 16:11:14

回答

2

你需要運行的foreach

foreach ($ret as $key => $item) { 
    for($i=1; $i<=$item; $i++) { 
     $insert[] = "('". mysql_real_escape_string($item) . "'," . $key . "')"; 
    } 
} 

內第二回路,並確保你的id是不是主要的唯一在表中。

+0

謝謝你,工作,並注意到! – ButtressCoral 2014-10-18 16:49:57