如何计算两个数组值

时间:2016-11-17 09:39:34

标签: php arrays

我有两个数组一个有数量,一个数组有价格我希望将两个数组相乘并找到它的总和

以下是两个数组

数量数组

Array
(
    [0] => 100
    [1] => 200
    [2] => 300
    [3] => 600
)

价格数组

Array
(
    [0] => 100
    [1] => 200
    [2] => 150
    [3] => 300
)

我想获得另一个数组,如果超过两个这样的数组

,它将给我总数
Array
(
    [0] => 10000
    [1] => 40000
    [2] => 45000
    [3] => 180000
)

以上是上述两个数组的倍数

到现在为止,我已经尝试了

    $quantity =  $_POST['quantity']; 
    $price =  $_POST['price']; 
    $total_price = array();
    foreach ($price as $key=>$price) {
    $total_price[] = $price * $quantity[$key];
    } 

但上面的方法给我错误

7 个答案:

答案 0 :(得分:3)

更改foreach语句,使用值中的主数组名称产生错误

foreach ($price as $key=>$price) {

将上述循环修改为: -

foreach ($price as $key=>$priceVal) {
  $total_price[] = $priceVal * $quantity[$key];
} 

答案 1 :(得分:3)

$quantity = $_POST['quantity']; 
$price = $_POST['price']; 
$total_price = array();

// assumption: $quantity and $price has same number of elements
// get total elements' count in variable. don't call count function everytime in loop.
$len = count($quantity);
for ($i=0; $i<$len; $i++) {
    $total_price[] = $price[$i] * $quantity[$i];
}

// var_dump($total_price) will give you desired output.

答案 2 :(得分:0)

尝试此更改:

$total_price[$key] = $price[$key] * $quantity[$key];

答案 3 :(得分:0)

遍历数组并将它们的元素分别相乘,将结果保存在第三个数组中?

results = array();
for($c = 0; $c < count($quantity); $c++) {
  $results[$c] = $price[$c] * $quantity[$c];
}

答案 4 :(得分:0)

$quantity =  $_POST['quantity']; 
$price =  $_POST['price']; 
$total_price = array();
$combine = array_combine($price,$quantity);

foreach ($combine as $price=>$quantity) {
    $total_price[] = $price * $quantity;
}

答案 5 :(得分:0)

<?php 
    $quantity = $_POST['quantity']; 
    $price = $_POST['price']; 
    $total_price = array(); 
    for ($i=0; $i<count($quantity); $i++) {
        $total_price[$i] = $price[$i] * $quantity[$i];
    }
?>

请试一试。

答案 6 :(得分:0)

你可以使用它,

$total_price = array_map("calculateTotal", $quantity, $price);
//print_r($total_price);

echo "Overall Price = " . array_sum($total_price);
function calculateTotal ($price, $qualitity) {
    return $price * $qualitity;
}