原始代码:
<?php
function calculateTotal($items) {
$total = 0;
for ($i = 0; $i < count($items); $i++) {
if (isset($items[$i]['price']) && isset($items[$i]['quantity'])) {
$total += $items[$i]['price'] * $items[$i]['quantity'];
}
}
return $total;
}
$items = [
['name' => 'item1', 'price' => 10, 'quantity' => 5],
['name' => 'item2', 'price' => 20, 'quantity' => 3],
// 更多项目...
];
echo calculateTotal($items);
?>
重构后的代码:
<?php
function calculateTotal(array $items): float {
return array_reduce(
array_filter($items, function ($item) {
return isset($item['price']) && isset($item['quantity']);
}),
function ($carry, $item) {
return $carry + ($item['price'] * $item['quantity']);
},
0. 0
);
}
$items = [
['name' => 'item1', 'price' => 10, 'quantity' => 5],
['name' => 'item2', 'price' => 20, 'quantity' => 3],
// 更多项目...
];
echo calculateTotal($items);
?>
重构原因解释:
1. **使用`array_filter`**:原代码通过循环和条件判断来检查每个项目的'price'和'quantity'是否存在。现在我们使用`array_filter`函数预先过滤出包含这两个键的项目,这样可以使计算总金额的逻辑更简洁。
2. **利用`array_reduce`**:重构后的代码用`array_reduce`函数替代了循环累加的过程。这个函数会对数组中的每个元素应用一个回调函数,并将结果累积到一个变量中,从而简化了累加操作。
3. **类型提示和返回值声明**:在函数定义中添加了类型提示(`array $items`),明确输入参数应为数组类型,同时在函数后声明返回值类型为`float`,提高了代码的可读性和安全性。
4. **初始化总金额为浮点数**:考虑到价格可能带有小数点,在`array_reduce`函数中将初始值设为`0.0