如何在PHP中求和数组值?

时间:2015-05-18 13:52:12

标签: php arrays

我有2数组变量我想将数组求和并分成两部分。请查看我的代码 -

print_r($public);

输出 -

Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 2
    [4] => 1
    [5] => 32
    [6] => 5
    [7] => 20
    [8] => 0
    [9] => 0
    [10] => 0
    [11] => 0
    [12] => 0
    [13] => 0
    [14] => 7
    [15] => 0
    [16] => 0
    [17] => 0
    [18] => 0
    [19] => 0
    [20] => 0
    [21] => 0
    [22] => 0
    [23] => 0
    [24] => 0
    [25] => 0
    [26] => 11
    [27] => 0
    [28] => 0
    [29] => 0
    [30] => 0
)



print_r($private);

Array
(
    [0] => 0
    [1] => 1
    [2] => 0
    [3] => 0
    [4] => 1
    [5] => 0
    [6] => 0
    [7] => 3
    [8] => 0
    [9] => 0
    [10] => 0
    [11] => 0
    [12] => 0
    [13] => 0
    [14] => 7
    [15] => 0
    [16] => 0
    [17] => 0
    [18] => 0
    [19] => 0
    [20] => 0
    [21] => 0
    [22] => 4
    [23] => 0
    [24] => 0
    [25] => 0
    [26] => 0
    [27] => 0
    [28] => 2
    [29] => 0
    [30] => 0
)

我的输出应该是 -

$variable1=array_sum($public) + array_sum($private); //for First 15 days(array)
$variable2 = array_sum($public) + array_sum($private); //For 16 to end of the array

$public$private是两个数组。续约May个月日期明智记录。我想将数组值加到两个除法部分。

  

第1天 - 1-15(数组0到14的总和)

     

第二天 - 月末16日(阵列15到阵列末尾的总和)

如何在一个行代码中将两个变量计算为两个除法部分?

1 个答案:

答案 0 :(得分:1)

您可以使用array_slice

 $first_part = array_sum(array_slice($public, 0, 15));
 $second_part = array_sum(array_slice($public, 15, 16));
 $first_part = array_sum(array_slice($public, 0, 15)) + array_sum(array_slice($private, 0, 15));
 $second_part = array_sum(array_slice($public, 15, 16)) + array_sum(array_slice($private, 15, 16));