在数组中连续添加每5个数字(PHP)

I have an array of numbers in the codes shown below.

$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);

$arrayCount = count($result_data);

for ($x = 0; $x < $arrayCount; $x++)
{
    if ($x%5==0)
    {
        $sum = $result_data[0] + $result_data[1] + $result_data[2] + $result_data[3] + $result_data[4];
        echo json_encode($sum);
        echo ("
");
    }       

}

And I got the result of:

15 15 15 15

Actually I wanted the results to be the sum of every 5 numbers in the array continuously and would expect the result to be:

15 40 65 90

Anyone knows how to get this?

You could reduce all of that code to:

$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
echo implode('
', array_map('array_sum', array_chunk($result_data, 5))),'
';

Which outputs:

15
40
65
90

See the man pages for:

try this:

$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);

$arrayCount = count($result_data);

for ($x = 0; $x < $arrayCount; $x++)
{
    if ($x%5==0)
    {
        $sum = $result_data[$x] + $result_data[$x+1] + $result_data[$x+2] + $result_data[$x+3] + $result_data[$x+4];
        echo json_encode($sum);
        echo ("
");
    }       

}

Instead of

$sum = $result_data[0] + $result_data[1] + $result_data[2] + $result_data[3] + $result_data[4]

you probably wanted

$sum = $result_data[$x] + $result_data[$x+1] + $result_data[$x+2] + $result_data[$x+3] + $result_data[$x+4]

Instead of referecing $result_data[1], $result_data[2], $result_data[3] etc you need to base the ID off your current $x value, like this

$sum = $result_data[$x] + $result_data[$x+1] + $result_data[$x+2] + $result_data[$x+3] + $result_data[$x+4]

A different approach

I would probably approach this in a different manner, continuously adding the values as I went along, and outputting the current total when I got to each fifth number, something like this:

$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);

$arrayCount = count($result_data);

$subtotal = 0;
for ($x = 0; $x < $arrayCount; $x++)
{
    $subtotal += $result_data[$x];
    if ($x%5==0)
    {
        echo json_encode($subtotal);
        echo ("
");
        $subtotal = 0;.
    }       

}

You can use:

$sum = $result_data[$x] + $result_data[$x+1] + $result_data[$x+2] + $result_data[$x+3] + $result_data[$x+4]

instead of:

$sum = $result_data[0] + $result_data[1] + $result_data[2] + $result_data[3] + $result_data[4];

since you've assigned $x inside your for loop.

Demo

Working demo

$result_data = range(1,20);
foreach($result_data as $key=>$value){
    if($value%5==0){
        echo $value+$result_data[$key-1]+$result_data[$key-2]
             +$result_data[$key-3]+$result_data[$key-4]."
";
    }
}

Output :

15

40

65

90