Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split flat array into groups/chunks of N elements then sum each group

I need to get a valid timestamp from the following array:

$arrkeys = array(
    "t" => [
        1442238840,60,120,180,240,300,360,420,480,540,600,660,720,780,840,900,960,
        1442239860,60,120,180,240,300,360,420,480,540,600,660,720,780,840,900,960,
        1442240880,60,120,180,240,300,360,420,480,540,600,660,720,780,840,900,960
    ]
);

I need to sum the first valid timestamp 1442238840 with the following 17 numbers together, to get a correct timestamp, and then, the second timestamp 1442239860, etc...

Example:

1442238840 + 60;
1442238840 + 120;
1442238840 + 180;
etc... 

I can't figure out how I could do this, some things I've tried:

Attempt No. 1

//Pseudo-code
foreach($arrkeys["t"] as $t){

    if(strlen($t) < 10){
        //Search for the first valid timestamp and sum?
    }

}

Attempt No. 2

//Not working.
$array_size = 17; 

/* I know that every 17 (counting from 0) have a  valid timestamp. 
    so that 0 = 1st valid timestamp, 20 = 2nd valid timestamp. */

for ($i = 0; $i < $array_size; $i++) { 
    do {
        echo $i;
    } while ($i > 0);

I don't know if I'm going the right way to solve this, I don't know how to do this efficiently, or at least do it.

Any suggestions?

like image 555
Max Avatar asked Apr 18 '26 18:04

Max


1 Answers

I love that you tried different things. That's good!

You tried to solve the problem yourself and array_chunk() will help you a lot here, since you can chunk your array into groups of 17 elements and then use array_sum() to sum each group of 17 elements together, e.g.

$result = array_chunk($arrkeys["t"], 17);
$result = array_map("array_sum", $result);
like image 155
Rizier123 Avatar answered Apr 20 '26 09:04

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!