【问题标题】:Multiply and add 2 arrays相乘和相加 2 个数组
【发布时间】:2017-01-06 17:10:58
【问题描述】:

我有两个变量,一个名为 $corp_resp:

var_dump($corp_resp)

字符串(3)“0.3”字符串(4)“0.35”字符串(3)“0.4”

其他:$corp_resp_template

var_dump($corp_res_template)´

字符串(3)“0.4”字符串(3)“0.6”字符串(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

最好的方法是什么?

【问题讨论】:

  • 你能告诉我们你到目前为止的尝试吗?
  • $sum = 0; for ($i==0; $i
  • @ChristopheCosta 这是我给你看的伪代码in the chatroom。看看一些基本的 for 循环语法,看看如何去做,而不是让别人为你写代码。而且,顺便说一句,这段代码中唯一缺少的是$i++ 函数之后的count() 部分(对不起,我认为这很明显可以跳过它)。
  • 你好 AL.G., $sum = 0; for($i = 0; $i

标签: php arrays add multiplication


【解决方案1】:

如果你的两个数组的长度相同,你可以运行类似:

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

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

【讨论】:

  • 此方法假定将字符串数组值正确转换为浮点数以进行乘法运算。
【解决方案2】:

写一个函数来实现它

$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);

【讨论】:

  • 您好,我尝试了您发送的两个代码并尝试了一些修改,但不起作用。
  • @ChristopheCosta“不工作”怎么办?请更具体。
  • 您好,问题出在数组中,请使用函数array_reduce。现在正在工作。感谢您的热心帮助。
猜你喜欢
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 2017-02-15
  • 1970-01-01
相关资源
最近更新 更多