简体   繁体   English

PHP将两个数字数组组合为一个数组

[英]PHP combine two number arrays into one array

I need a new array combining 2 array with calculation 我需要一个将2个数组与计算相结合的新数组

$array1 = array(2,5,7,1);

$array2 = array(1,3,2,5);

result array should out put 结果数组应该放在外面

$array3 = array(3,8,9,6);

is this possible in php i know array_merge function combine two array but how combine after calculation 在PHP中这可能吗我知道array_merge函数合并两个数组,但是计算后如何合并

NOTE : 注意 :

this is possible in C# but i want to know can i do it php as well 这在C#中是可能的,但是我想知道我也可以做到php

If they are guaranteed to be matched in size then you can use something like this 如果保证它们的大小匹配,则可以使用类似的内容

$array3 = array();

for($x =0; $x<count($array1); $x++){
     $array3[] = $array1[$x] + $array2[$x];
}

If the arrays are not guaranteed to be of the same size you can do the following 如果不能保证数组大小相同,则可以执行以下操作

$array3 = array();
$max = max(count($array1), count($array2));
for($x =0; $x<$max; $x++){
     $array3[] = (isset($array1[$x])?$array1[$x]:0)) + (isset($array2[$x])?$array2[$x]:0));
}  

With the adoption of PHP 7 and it's null coalesce operator this code becomes much more readable: 随着PHP 7的采用以及它的null合并运算符,此代码变得更加可读:

$array3 = array();
$max = max(count($array1), count($array2));
for($x =0; $x<$max; $x++){
     $array3[] = ($array1[$x] ?? 0) + ($array2[$x] ?? 0);
}  

For this you have to use foreach loop 为此,您必须使用foreach循环

<?php
$array1 = array(2,5,7,1);
$array2 = array(1,3,2,5);
$array3= array();


foreach($array1 as $key=>$value)
{
   $array3[$key] = $array1[$key]+$array2[$key];
}

print_r($array3)
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM