乘以并添加2个数组

时间:2017-01-06 17:10:58

标签: php arrays add multiplying

我有两个名为$corp_res p:

的变量
var_dump($corp_resp)
  

string(3)“0.3”string(4)“0.35”string(3)“0.4”

其他:$corp_resp_template

var_dump($corp_res_template)´
  

string(3)“0.4”string(3)“0.6”string(3)“0.8”

我想添加和乘以数组:

$total = (0.3*0.4)+(0.35*0.6) +(0.4*0.8) => 0,12+0.21+0,32 

$total = 0.65

最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

如果两个阵列的长度相同,则可以运行:

array_sum(array_map(
    function($resp, $tpl){ return $resp * $tpl; }, 
$corp_resp, $corp_res_template));

如果数组的长度不相等,则较长数组的尾部将被计算为(数字* 0),因此在将最终结果相加时忽略它们

答案 1 :(得分:1)

编写一个函数来执行此操作

$corp_resp = array("0.3", "0.35", "0.4");
$corp_res_template = array("0.4", "0.6", "0.8");

function add_products($a1, $a2) {
    if (!is_array($a1)) {
            throw new Exception("a1 is not an array");
    }
    if (!is_array($a2)) {
            throw new Exception("a2 is not an array");
    }
    if (sizeof($a1) != sizeof($a2)) {
            throw new Exception("Arrays don't have same number of elements");
    } 

    // both params are arrays and have same number of elements!

    $count = sizeof($a1);
    $multiplied = array();
    for($i=0; $i<$count; $i++) {
            // we assume that each element is a string representing a floatval so we need to cast as a float before multiplying
            $multiplied[$i] = floatval($a1[$i]) * floatval($a2[$i]);
    }
    return array_sum($multiplied);
}

$val = add_products($corp_resp, $corp_res_template);

var_dump($val);