2016-11-17 92 views
1

我有兩個數組的一個數量與一個陣列的價格我要乘以陣列的兩個,並發現其和如何計算兩個數組值

這裏有兩個數組

數量陣列

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]; 
    } 

但上述方法給我的錯誤

+0

你可以做手工或使用功能。 –

+3

[在PHP乘兩個數組值]的可能的複製(http://stackoverflow.com/questions/14270502/multiply-two-array-values-in-php) –

+2

你看到什麼錯誤? –

回答

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. 
3

更改foreach語句,使用主數組名稱中的值產生錯誤

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

修改上面的迴路: -

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

嘗試這種變化:通過陣列

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

發生了什麼變化? –

1

迭代地和單獨地倍增它們的元素保存結果中的第三陣列?

results = array(); 
for($c = 0; $c < count($quantity); $c++) { 
    $results[$c] = $price[$c] * $quantity[$c]; 
} 
0
$quantity = $_POST['quantity']; 
$price = $_POST['price']; 
$total_price = array(); 
$combine = array_combine($price,$quantity); 

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

解釋你做了什麼以及爲什麼這樣做會有幫助 – empiric

+0

use array_combine();用於組合單價中的價格和數量。在這個數組價格中作爲關鍵和數量值作爲價值。之後多重這個價值並收集在$ total_price中 – abhayendra

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

請試試這個。

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; 
}