我有一个具有不同值的动态变量
$a = (1,2,3,4,5);
$a = (2,3,4,5,6);
我想要一个将每个数组的每个索引求和的结果
$a = (3,5,7,9,11);
while($row=mysqli_fetch_array($sql)){
$a = explode(',',$row['array']); //array with same variable name
}
答案 0 :(得分:0)
您可以使用array_map:
$a = array();
while($row=mysqli_fetch_array($sql)){
$a = array_map(function ($x, $y) { return $x + $y; }, $a, explode(',',$row['array']));
}
print_r($a);
假设您的代码返回
行$row['array'] = '1,2,3,4,5';
$row['array'] = '2,3,4,5,6';
输出将是:
Array
(
[0] => 3
[1] => 5
[2] => 7
[3] => 9
[4] => 11
)
答案 1 :(得分:0)
可能会低于代码将帮助您
$a = array(1,2,3,4,5,4,5);
$b = array(2,3,4,5,6,7,3);
foreach($a as $k=>$v)
{
$temp = $a[$k]+$b[$k];
$c[] = $temp;
}
print_r($c);