我需要从此创建的数组中插入所有内容:
$test = $_POST['productinfo'];
$total2 = 0;
$totalquantity = 0;
$totalamount = 0;
for($i=0; $i < sizeof($test); $i++) {
list($name, $quantity, $total) = explode("|", $test[$i]);
echo "Name: ".$name;
echo "<br>";
echo "Amount: ".$quantity;
echo "<br>";
echo "Price: ".$total . "€";
echo "<br>";
echo "<br/>";
$total2 += $total;
$totalquantity += $quantity;
$names[] = $name;
$totalamount++;
}
$_SESSION['totalprice'] = $total2;
$_SESSION['totalquantity'] = $totalquantity;
for($i=0; $i < $totalamount; $i++) {
$_SESSION['product'] = $name[$i] ;
print_r($names[$i]);
}
在单个变量内进入数据库,该变量为$_SESSION['product'] = $name[$1]
,但不能仅凭此变量将所有内容输入数据库,有没有办法将数组中的所有数据推入单个变量然后可以用来将所有内容插入数据库的特定行中?
答案 0 :(得分:1)
正如我在评论中提到的那样,尝试使用json_encode
将数组存储为字符串。
$test = $_POST['productinfo'];
$total2 = 0;
$totalquantity = 0;
$totalamount = 0;
for($i=0; $i < sizeof($test); $i++) {
list($name, $quantity, $total) = explode("|", $test[$i]);
echo "Name: ".$name;
echo "<br>";
echo "Amount: ".$quantity;
echo "<br>";
echo "Price: ".$total . "€";
echo "<br>";
echo "<br/>";
$total2 += $total;
$totalquantity += $quantity;
$names[] = $name;
$totalamount++;
}
$_SESSION['totalprice'] = $total2;
$_SESSION['totalquantity'] = $totalquantity;
$_SESSION['product'] = json_encode($names) ;
您应该可以通过打印出来查看其存储方式
print_r(json_encode($names));
要返回数组,只需使用json_decode
函数
$names = json_decode($_SESSION['product'], true);
答案 1 :(得分:0)
您可以使用json_encode像这样序列化数组:
$your_var_for_DB = json_encode($_SESSION['product']);
,然后在插入查询中使用$ your_var_for_DB。
要在其他地方重用该值,则需要像这样解码它:
$your_var = json_decode($your_db_var);
和$ your_var将成为您包含所有数据的数组。