2012-12-31 45 views
0

我已經搜索了一個針對我的問題的simliar解決方案,但是我正在努力尋找它,所以請原諒,如果這已被問到。我有我的PHP代碼,這樣根據鍵值將數組插入到mysql中

foreach($data['cells'] as $row) { 
    print_r($row); 
} 

產生

Array 
(
    [1] => ASSET ID 
    [2] => SERIAL IN CAPS 
    [3] => COMPANYASSETTAG 
    [4] => DATE RCVD 
    [5] => MFR 
    [6] => Type 
    [7] => MODEL 
    [8] => PRINTER MODEL COMMENTS 
    [9] => PART NUMBER 
    [10] => R ID 
    [11] => GRADE 
    [12] => PRICE 
    [13] => COLOR CAPABLE (Color or Monochrome) 
    [14] => COSMETICALLY ACCEPTABLE (Yes or No) 
    [15] => PRINTERCABLEINCLUDED (Yes or No) 
    [16] => PRINTER TECHNOLOGY (Laser, Inkjet, 4-1 Laser, 3-1 Laser, 4-1 Ink Jet, 3-1  Ink Jet, Dot Matrix, Plotter, Solid Ink, Thermal) 
    [17] => DUPLEX (Yes or No) 
    [18] => MULTIFUNCTION (Yes or No) 
    [19] => COMMENT (reason) 
    [20] => COSMETICS COMMENT 
    [21] => PURCHASE ORDER # (Trailer #) 
    [22] => WAYBILL# 
) 
Array 
(
    [1] => CNGYF04230 
    [2] => CNGYF04230 
    [3] => MISSING 
    [4] => 28/12/2012 
    [5] => Hewlett Packard 
    [6] => Multi-Function Printers 
    [8] => 4345X 
    [9] => Q3943A 
    [11] => G 
    [13] => Monochrome 
    [14] => Yes 
    [15] => No 
    [16] => Laser 
    [17] => Yes 
    [18] => Yes 
    [21] => TRDS293 
    [22] => HM693800 
) 

正如你可以看到關鍵的第二陣列中失蹤的人相比,上述陣列。這些對應於列。第二部分缺失的原因是因爲這些字段不包含任何數據。我希望能夠根據鍵將這些插入到mysql表中相應的字段中。

例如

foreach($data['cells'] as $row) { 
    //print_r($row); 
    $sql = "INSERT INTO table (asset_id,serial_in-caps...) VALUES ('$row[0]','$row[1]'...)"; 
} 
+0

你應該*永遠不會*以這種方式生成你的查詢字符串。 http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php –

回答

2

當你有一個數字爲數組中的鍵,你可以通過你的陣列,一個for循環迴路:

$keys = array(); 
foreach($data["cells"] as $row) { 
    if(empty($keys)) { 
     $keys = $row; 
     continue; 
    } 

    $rowValues = array(); 
    for($i = 1; $i < count($keys); $i++) { 
     if(isset($row[$i])) 
      $rowValues[] = $row[$i]; 
     else 
      $rowValues[] = "NULL"; //(or another standard value) 
    } 
    /* continue with the variable $rowValues */ 
} 

我希望它可以幫助...

+0

這對於($ i = 0; $ i

1

我只是找到了解決辦法。

foreach($data['cells'] as $row) { 
    //print_r($row); 
    foreach($row as $key => $value) { 
     echo "$key is at $value<br>"; 
    } 
} 
0

@atreju

你的代碼很完美,只是清理了一些丟失的字符:)

$keys = array(); 
foreach($data["cells"] as $row) { 
    if(empty($keys)) { 
     $keys = $row; 
     continue; 
    } 

    $rowValues = array(); 
    for($i = 1; $i <= count($keys); $i++) { 
     if(isset($row[$i])) 
      $rowValues[] = $row[$i]; 
     else 
      $rowValues[] = "NULL"; //(or another standard value) 
     } 
    /* continue with the variable $rowValues */ 
} 
+0

我認爲'<= count($ keys)'應該只是' atreju

+0

現在你提到,我需要找出它爲什麼從1開始,而不是0 :)謝謝 –