[英]How to insert multidimensional array in php?
只是我先前問題的一個后續問題 。 通過從數組獲取值,我的代碼是這樣的:
for ($i=0; $i<count($entries);$i++)
{
$pcode = substr($entries[$i][0],0,-2);
$sku = substr($entries[$i][0],2);
$aprice = $entries[$i][1];
$beginv = $entries[$i][2];
$delivery = $entries[$i][3];
$endinv = $entries[$i][4];
$offtake = $entries[$i][5];
$bo = $entries[$i][6];
$shelf = $entries[$i][7];
$gondola = $entries[$i][8];
$chillers = $entries[$i][9];
$mass = $entries[$i][10];
$other = $entries[$i][11];
$total = $entries[$i][12];
$statement = "INSERT INTO `report_details` VALUES ('$id', '$pcode', '$sku', '$aprice', '$beginv', '$delivery', '$endinv', '0', '0', '$offtake, '0', '0', '0', '$bo', '$shelf', '$gondola', '$chillers', '$mass', '$other', '$total')";
$result = mysqlparseradd($statement,$db);
if($result)
{echo "YES";}
else
{echo "NO";}
}
我的數組是這樣的:
Array
(
[0] => Array
(
[0] => 0111
[1] => 260.00
[2] => 23
[3] => 34
[4] => 3
[5] => 54
[6] => 1
[7] => 2
[8] => 4
[9] => 5
[10] => 12
[11] => 23
[12] => 46
)
[1] => Array
(
[0] => 0214
[1] => 22.00
[2] => 32
[3] => 4
[4] => 11
[5] => 25
[6] => 4
[7] => 12
[8] => 23
[9] => 5
[10] => 2
[11] => 2
[12] => 44
)
[2] => Array
(
[0] => 0313
[1] => 25.00
[2] => 5
[3] => 52
[4] => 12
[5] => 45
[6] => 12
[7] => 5
[8] => 6
[9] => 7
[10] => 12
[11] => 3
[12] => 33
)
)
這樣的事情,我總是得到NO
的值,這意味着它不會被添加到數據庫中。 我的問題是,沒有插入數據庫的代碼有什么問題? 當我只插入一行數據但沒有多行數據時,我做的很好。
編輯
當我打印$statement
,結果是這樣的:
INSERT INTO `report_details` VALUES ('JJ1234567890_140822_140824_1020001', '01', '11', '260.00', '23', '34', '3', '0', '0', '54, '0', '0', '0', '1', '2', '4', '5', '12', '23', '46')
僅添加一個數組值。 我的mysqlparseradd
是一個類似於mysqli_query
的函數。 它執行查詢。
您有語法錯誤。
用這個。
$statement = "INSERT INTO `report_details` VALUES ('$id', '$pcode', '$sku', '$aprice', '$beginv', '$delivery', '$endinv', '0', '0', '$offtake', '0', '0', '0', '$bo', '$shelf', '$gondola', '$chillers', '$mass', '$other', '$total')";
當前解決方案的另一種方法,使用數組映射和一個函數來構建value子句的數組並將其插入一次。
<?php
$statement = "INSERT INTO `report_details` VALUES ".implode(',', array_map(function($entry) use ($id) {return(format_row($id, $entry));}, $entries));
$result = mysqlparseradd($statement,$db);
if($result)
{
echo "YES";
}
else
{
echo "NO";
}
function format_row($id, $entry)
{
$pcode = substr($entry[0],0,-2);
$sku = substr($entry[0],2);
$aprice = $entry[1];
$beginv = $entry[2];
$delivery = $entry[3];
$endinv = $entry[4];
$offtake = $entry[5];
$bo = $entry[6];
$shelf = $entry[7];
$gondola = $entry[8];
$chillers = $entry[9];
$mass = $entry[10];
$other = $entry[11];
$total = $entry[12];
return "('$id', '$pcode', '$sku', '$aprice', '$beginv', '$delivery', '$endinv', '0', '0', '$offtake', '0', '0', '0', '$bo', '$shelf', '$gondola', '$chillers', '$mass', '$other', '$total')";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.