我的代码@Teh Playground
我正在使用这个数组:
$products = array (
'location1' => array (
'apples' => array (
'stock' => 100,
'backorder' => 50
),
'oranges' => array (
'stock' => 250,
'backorder' => 100
),
),
'location2' => array (
'apples' => array (
'stock' => 200,
'backorder' => 50
),
'oranges' => array (
'stock' => 100,
'backorder' => 50
),
'pears' => array (
'stock' => 30,
'backorder' => 70
)
)
);
所需输出:一个数组,其中包含所有位置的库存/缺货中所有产品的单独总和。请注意,并非所有产品都会出现在每个位置(梨就是一个例子),因此必须动态创建用于汇总库存/缺货总额的产品列表。
$overview = array (
'apples' => array (
'stock' => 300,
'backorder' => 100
),
'oranges' => array (
'stock' => 350,
'backorder' => 150
),
'pears' => array (
'stock' => 30,
'backorder' => 70
)
);
我编写了下面的代码试图完成此任务......
$overview = array();
foreach($products as $location => $inventory){
foreach($inventory as $product => $properties){
foreach($properties as $type => $number){
$overview[$product][$type] += $number;
}
}
}
...但它会引发我不知道如何修复的错误:
Warning: Undefined array key "apples" in Standard input code on line 35
Warning: Undefined array key "stock" in Standard input code on line 35
Warning: Undefined array key "backorder" in Standard input code on line 35
Warning: Undefined array key "oranges" in Standard input code on line 35
Warning: Undefined array key "stock" in Standard input code on line 35
Warning: Undefined array key "backorder" in Standard input code on line 35
Warning: Undefined array key "pears" in Standard input code on line 35
Warning: Undefined array key "stock" in Standard input code on line 35
Warning: Undefined array key "backorder" in Standard input code on line 35
我已经搜索过了,但这个问题似乎与我遇到的不同。这里最好的方法是什么?
使用时
$overview[$product][$type] += $number;
+=
操作员基本上会执行3个步骤,
$overview[$product][$type]
$number
$overview[$product][$type]
问题出现在第一步。
--
您的
$overview
数组一开始为空,因此 $overview[$product]
(即 $overview["apples"]
)还不存在,因此读取当前值(步骤 1)会引发警告。
最明显的修复是为数组的两个级别提供安全的“默认”初始值。
类似:
foreach ($products as $location => $inventory) {
foreach ($inventory as $product => $properties) {
foreach ($properties as $type => $number) {
$overview[$product] = $overview[$product] ?? [];
$overview[$product][$type] = $overview[$product][$type] ?? 0;
$overview[$product][$type] += $number;
}
}
}