将3个不同数组的各列相加

时间:2016-11-07 11:02:15

标签: php arrays

对3个不同数组的各列进行求和

我需要对各列的数组求和

$a = [1,2,3,4];
$b = [5,6,8,7];
$c = [10,11,4,70];

输出将是那样..

$d = [(1+5+10),(2+6+11),(3+8+4),(4+7+70)];

然后$ d将

$d = [16,19,15,81];

3 个答案:

答案 0 :(得分:1)

以下是代码:

$a = [1,2,3,4];
$b = [5,6,8,7];
$c = [10,11,4,70];
$limit = count($a);
$d = array();
for($i=0;$i<$limit;$i++){
    $d[] = $a[$i]+$b[$i]+$c[$i];
}
var_dump($d);//array(16,19,15,81)

我希望它有所帮助

答案 1 :(得分:0)

$a = [1,2,3,4];
$b = [5,6,8,7];
$c = [10,11,4,70];
$res = [];

for($i=0;$i<sizeof($a);$i++)
{
  $res[$i]=$a[$i]+$b[$i]+$c[$i];
}

答案 2 :(得分:0)

您可以尝试这样

&#13;
&#13;
$a = [1,2,3,4];
$b = [5,6,8,7];
$c = [10,11,4,70];
$myArray = array($a, $b, $c);

$sumArray = array();

foreach ($myArray as $k=>$subArray) {
  foreach ($subArray as $id=>$value) {
    $sumArray[$id]+=$value;
  }
}

print_r($sumArray);
&#13;
&#13;
&#13;