php - 如何更新购物篮并更改多维数组中的产品数量?
问题描述
我在篮子阵列中有这个产品:
array(3) {
[0]=>array(3) {
["product_id"]=>string(2) "35"
["po"]=>array(2) {
[0]=>array(1) {
["size"]=>string(1) "M"
}
[1]=>array(1) {
["material"]=>string(10) "Cotton"
}
}
["qty"]=>string(1) "1"
}
[1]=>array(3) {
["product_id"]=>string(2) "34"
["po"]=>int(0)
["qty"]=>string(1) "2"
}
[2]=>array(3) {
["product_id"]=>string(2) "35"
["po"]=>array(2) {
[0]=>array(1) {
["size"]=>string(3) "XXL"
}
[1]=>array(1) {
["material"]=>string(10) "Cotton"
}
}
["qty"]=>string(1) "2"
}
}
我需要更新 product_id = 35 的数量,其中 size = XXL。是否可以这样做,我应该使用什么参考来准确更新该记录(您可以看到带有键 [0] 的数组也包含有关此 product_id 35 的信息)?
如果我需要更改同一产品的“材料”或“尺寸”,我也有同样的问题。谢谢您的宝贵时间!
解决方案
您可以迭代您的产品列表并检查所需条件以查找要修改的元素。像这样的东西。
<?php
$products = [
[
'product_id' => '35',
'po' => [
[
'size' => 'M',
],
[
'material' => 'Cotton',
],
],
'qty' => '1',
],
[
'product_id' => '34',
'po' => 0,
'qty' => '2',
],
[
'product_id' => '35',
'po' => [
[
'size' => 'XXL',
],
[
'material' => 'Cotton',
],
],
'qty' => '2',
],
];
foreach ($products as $productKey => $product) {
if ('35' !== $product['product_id']) {
continue;
}
if (!\is_array($product['po'])) {
continue;
}
foreach ($product['po'] as $poItem) {
if ($poItem['size'] && 'XXL' === $poItem['size']) {
$products[$productKey]['qty'] = '500';
}
}
}
var_dump($products);
推荐阅读
- udp - 从 cap 文件中读取数据包数据
- python - Pandas groupby 与 lambda 并在列表中
- python - 如何设置 Requests 贡献的开发环境?
- magento - phpmyadmin 不允许我创建数据库
- java - 设置 CountDownTimer 以运行 onDestroy() 的正确方法是什么?
- mysql - MySQL 选择具有属性和属性值的产品 - 分组
- node.js - Stripe 订阅未更新数量
- angular - cdk virtual-scroll inside mat-select for mat-option
- android - React Native android release compilation AAPT2 error. PNG chunk is too large
- python-3.x - How to use non-top-level functions in parallelization?