首页 > 解决方案 > 如何更新购物篮并更改多维数组中的产品数量?

问题描述

我在篮子阵列中有这个产品:

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 的信息)?

如果我需要更改同一产品的“材料”或“尺寸”,我也有同样的问题。谢谢您的宝贵时间!

标签: phparraysmultidimensional-array

解决方案


您可以迭代您的产品列表并检查所需条件以查找要修改的元素。像这样的东西。

<?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);

推荐阅读