[英]How to update shopping basket and change the product quantity in multidimensional-array?
我在籃子陣列中有這個產品:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.