Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php在多数组上减少值_Php_Arrays - Fatal编程技术网

php在多数组上减少值

php在多数组上减少值,php,arrays,Php,Arrays,您好,我是新手,我必须减少数组中的值,但有一些困难,如果有人可以给我我的问题的方向提前感谢 我有一个$id=>$quantity的产品数组 array:4 [▼ 43 => 3; 44 => 2; 47 => 2; 51 => 2; ] 此属性表示餐厅的产品购物车此购物车可分为3类,如主菜、菜肴、甜点 主菜 array:2 [▼ 43 => 3; 44 => 2; ] 盘子 甜点 array:1[▼ 51 => 2; ]

您好,我是新手,我必须减少数组中的值,但有一些困难,如果有人可以给我我的问题的方向提前感谢

我有一个$id=>$quantity的产品数组

array:4 [▼
  43 => 3;
  44 => 2;
  47 => 2;
  51 => 2;
]
此属性表示餐厅的产品购物车此购物车可分为3类,如主菜、菜肴、甜点

主菜

array:2 [▼
  43 => 3;
  44 => 2;
]
盘子

甜点

array:1[▼
  51 => 2;
]
如果我增加一份菜单,我必须减少一道主菜、一道菜和一份甜点。 我知道如何减少这样的数组:

$cart[$idEntree]--;
但是,如果我有2个或更多产品,我如何选择id以减少一个产品中的值,以及在产品值=0后减少下一个产品

例如,我将减少主菜阵列的4个菜单:

array:2 [▼
  43 => 3;
  44 => 2;
]
在此之后,我有:

array:2 [▼
  43 => 0;
  44 => 1;
]

如果您能帮助我,谢谢。

您希望在阵列上循环
foreach

$selections=[
43 => 3,
44 => 2
];
foreach($key=>$value){
如果($value>0){
$selections[$key]-=1;
}否则{
$selections[$key]=0;
}
}
变量转储($选择);
//阵列(2){
//  [43]=>
//int(2)
//  [44]=>
//int(1)
//}

这应该适用于您的情况:

$products_to_subtract = 4;

foreach ($array as $id => $value) {
    while($value && $products_to_subtract)
    {
        $array[$id] = --$value;
        $products_to_subtract--;
    }
}

只需将
foreach
一起使用,而
循环:

$entre=[
43 => 3,
44 => 2
];
$i=1;
$count=4;
foreach($id=>$value的主菜){
而($0
[44] => 2
)

对于我的解决方案,我放置了一个变量,该变量在每个循环中递减,以避免减少太多的产品

$quantityPlatLoop = $quantityMenuVerif;
        for ($i = 0; $i < $quantityMenuVerif ;$i++){
            foreach($platCalculQuantity as $idPlatQuantity => $platQuantity){
                if($cart[$idPlatQuantity] >= 1 && $quantityPlatLoop >= 1){
                    $cart[$idPlatQuantity]--;
                    $quantityPlatLoop--;

                }

            }

        }
$quantityPlatLoop=$quantityMenuVerif;
对于($i=0;$i<$QuantityMenurif;$i++){
foreach($platCalculQuantity作为$idPlatQuantity=>$platQuantity){
如果($cart[$idPlatQuantity]>=1&&$quantityPlatLoop>=1){
$cart[$idPlatQuantity]--;
$quantityPlatLoop--;
}
}
}

他们想要
[43=>0;44=>1]
您的输出是
[43=>2;44=>1]
?对于每个选项,您同时在每个$key上搜索1。我想在所有组中搜索4,而不是在第一次和第二次搜索4。如果我只减少一个,我只希望搜索43=>3或44=>2,我尝试了这个解决方案,但没有成功,但非常感谢。
$quantityPlatLoop = $quantityMenuVerif;
        for ($i = 0; $i < $quantityMenuVerif ;$i++){
            foreach($platCalculQuantity as $idPlatQuantity => $platQuantity){
                if($cart[$idPlatQuantity] >= 1 && $quantityPlatLoop >= 1){
                    $cart[$idPlatQuantity]--;
                    $quantityPlatLoop--;

                }

            }

        }