添加两个数组变量

时间:2015-07-17 15:12:09

标签: php arrays variables

我有$ product ['price']和$ option ['price'],我想将这两个加在一起并回显结果。这些是两个独立的数组,例如$ product = array {price => 1}和$ option = array {price => 1}

这可能吗?

2 个答案:

答案 0 :(得分:2)

对于一个选项,就像你提到的那样:

$total = $product['price'] + $option['price'];
echo $total;

对于多个选项,假设您有一个$ options数组:

$total = $product['price'];
foreach ($options as $option) {
    $total = $total + $option['price'];
}
echo $total;

答案 1 :(得分:1)

$sum = $product['price'] + $option['price'];

如果有很多价格,例如$ option [' price'] [0],$ option [' price'] [1]等等,那么添加全部价格,我们可以做到以下几点:

$sum = $product['price'];
foreach ($option['price'] as $key => $value) {
    $sum = $sum + $value;
}

echo $sum;