【问题标题】:How to make an array from the deference between two arrays?如何从两个数组之间的差异中创建一个数组?
【发布时间】:2019-06-27 15:10:16
【问题描述】:

我正在制作一个在线购物车。所以我想在确认我的产品后更新我的总库存......我能够从用户那里获取数量,并且我能够从 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 Query中更新... 我已经尝试了一切。请帮帮我...

【问题讨论】:

  • 当您说您已经尝试了所有方法时,您能详细说明您尝试过但没有成功的事情吗?

标签: php mysqli


【解决方案1】:

如果索引相等,则以下代码可以工作:

$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

【讨论】:

  • 谢谢您,先生,非常感谢...您能否告诉我在 STOCK 列的 PRODUCT 表中名为 CART 的数据库中更新这些值的查询...我的意思是我们得到的数组 array(4) { [0]=> int(90) [1]=> int(88) [2]=> int(36) [3]=> int(84) } 它应该更新90 在 STOCK 列中,其中 ID = IN (' . implode(",", $product) . ') 等等..
  • 能否附上获取数据的查询?
  • $connect = mysqli_connect('localhost', 'root', '', 'cart'); $query = 'SELECT stock FROM products WHERE id IN (' . implode(",", $product) . ')'; $result = mysqli_query($connect, $query);这个连接到mysqli
  • 先生,我已将我的产品 ID 存储在 $product... 所以,我应该将 'id_product' => $entry['id'] 重命名为 $product=> $entry['id' ],或 implode(',',$product) => $entry['id'],对不起,先生,我真的是 mysql 代码中的大人物
  • 如果变量存储的数量超过 id,则不应重命名变量。想象一下,每个产品都提供一组信息:产品名称、类别和 ID,我们可以通过这些信息唯一地找到您的记录。在 $products 中,您将保存一系列产品,在 $product 中只有一个。这种方法使得编写可读代码成为可能,例如foreach($products as $product).
猜你喜欢
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 2016-07-21
  • 1970-01-01
  • 2021-12-06
相关资源
最近更新 更多