基于相同键复用数组值

时间:2017-04-21 18:11:01

标签: php

我们说我有两个这样的数组:

Array1 ( [scholarshipId] => 8 [studentId] => 2571 [weightage] => ["20","20","20"] )

另一个是:

Array2 ( [0] => Array ( [weightage] => ["60","20","20"] ) )

现在我想要乘以weightage的值,然后计算总和。

请帮帮我。

2 个答案:

答案 0 :(得分:0)

$value = $array1['weightage'][0] * $array2['weightage'][0];
$value2 = $array1['weightage'][1] * $array2['weightage'][1];
$value3 = $array1['weightage'][2] * $array2['weightage'][2];
$sum = $value + $value2 + $value3

那样的东西?

答案 1 :(得分:0)

这里我们收集数组$result中的值的乘积,然后最后添加函数array_sum

的数组值

Try this code snippet here

<?php

ini_set('display_errors', 1);
$array1 = Array(
    "scholarshipId" => 8,
    "studentId" => 2571,
    "weightage" => ["20", "20", "20"]
     );
$array2 = Array(
           0 => Array(
                "weightage" => ["60", "20", "20"]
               )
         );

$result=array();
foreach($array1["weightage"] as $key => $value)
{
    $result[]=$value*$array2[0]["weightage"][$key];
}

print_r(array_sum($result));