Question

I have make many changes but still cannot figure out. i have an array let say: [1,2,3,4,5,6,7,8,9,10] i just want to ask how to add this array until index 2 and continued add for rest array then divide them by 2 array each.

input : [1,2,3,4,5,6,7,8,9,10 ];

process : [1+2+3, 4+5+6, 7+8+9, 10]

output i need : [6,15,24,10]

then i want to cut this array into 2

last output : [[6,5],[24,10]]

Thanks

Was it helpful?

Solution

Your code will be:

$data   = range(1,10);
$result = array_chunk(array_map('array_sum', array_chunk($data, 3)), 2);

-please, read array functions manual

OTHER TIPS

Something like this?

<?php
$array = range(1, 10);

$array = array_chunk($array, 3);

$array = array_map('array_sum', $array);

$array = array_chunk($array, 2);

print_r(
    $array
);

/*
    Array
    (
        [0] => Array
        (
            [0] => 6
            [1] => 15
        )
        [1] => Array
        (
            [0] => 24
            [1] => 10
        )
    )
*/

I think you can use a for cycle to sum what you need then store result in new array. Another solution is using array merge. When you've done the trick you can create a multidimensional array to get the result like [[6,5],[24,10]].

Hope it helps

Can't really see what you are getting at from the question, but I think PHP's array_chunk command may be your friend on this, http://www.php.net/manual/en/function.array-chunk.php

this will allow you to split the array into chunks of 3 (or any number) of elements with last element containing the remainder (in this case 1 element)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top