我正在制作一个在线购物车。所以我想在确认我的产品后更新总库存...我能够从用户那里捕获数量,而且能够从MYSQL中捕获数据。现在,我想根据我的MYSQL数量和用户数量之间的差异创建一个数组,并在购买后更新我的总库存...
我的MYSQL数组输出为:
print_r($ qty);
Array ( [0] => Array ( [stock] => 100 ) [1] => Array ( [stock] => 100 ) [2] => Array ( [stock] => 50 ) [3] => Array ( [stock] => 100 ) )
和
我的用户阵列输出为:
print_r($ _SESSION ['productqty']);
Array ( [0] => 10 [1] => 12 [2] => 14 [3] => 16 )
我想制作一个像这样的数组
Array ( [0] => 90 [1] => 88 [2] => 36 [3] => 84 )
此数组是两个数组之间的区别,它将在MYSQLI查询中更新... 我已经尝试了一切。请帮助我...
答案 0 :(得分:2)
如果索引相等,则以下代码可以工作:
$remaining = [];
// iterate $qty rows and fill $remaining array
foreach($qty as $index => $entry) {
$remaining[] = $entry['stock'] - $_SESSION['productqty'][$index];
}
var_dump($remaining);
编辑:将更新的库存存储在数据库中
首先,有必要在第一个查询中选择产品的ID,以便以后可以更新它们。此步骤应导致以下转储(除了正确的ID)
Array (
[0] => Array ( [id] => 12, [stock] => 100 )
[1] => Array ( [id] => 37, [stock] => 100 )
[2] => Array ( [id] => 39, [stock] => 50 )
[3] => Array ( [id] => 50, [stock] => 100 )
)
现在,您可以通过将产品ID附加到阵列上来优化计算:
remaining = [];
foreach($qty as $index => $entry) {
$remaining[] = [
'id_product' => $entry['id'],
'stock' => $entry['stock'] - $_SESSION['productqty'][$index]
];
}
现在,您可以存储更新的库存了:
foreach($remaining as $entry) {
// Perform your SQL-Operation, something like:
// UPDATE products SET stock = $entry['stock'] WHERE id = '$entry['id']
}
注意:请确保您的应用程序不受SQL注入的影响。 看看:https://en.wikipedia.org/wiki/SQL_injection