0

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

2
  • Combination of array_chunk() (with a size argument of 3), array_map() or array_walk() doing an array_sum() to add the groups of values; then array_chunk() again with a size argument of 2 Commented Oct 22, 2013 at 9:40
  • Thank Mark Barker. Got solution already :P Commented Oct 23, 2013 at 1:07

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

It works!!..Hi Alma Do Mundo, thank you for this solution. :)
1

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
        )
    )
*/

1 Comment

Hi Anthony Sterling, thank you for this solution. Your solution work too.. :)
0

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

1 Comment

Already got solution from Alma Do Mundo and Anthony Sterling. By the way, thanks Stefano Bosio :)
0

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)

1 Comment

i wanna use for the google chart. By the way, got answer already. Thanks Pete Ravenscroft :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.