0

Supposing I have an Array with x elements. I would like to loop through this Array in "tens" and add a run-Time variable. This means that each set of 10 Arrays will have a unique run-time. I am using the code below:

$time = '00:00:00';
 $k = 0;
    for ($i = 0; $i < count($agnt_arr); $i+=10) {
        $temp = strtotime("+$k minutes", strtotime($time));
        $runTime = date('H:i', $temp);
        array_push($agnt_arr[$i], $runTime);
        $k+=4;
    }

Where $agnt_arr is an Array with the following structure :

Array
(
    [0] => Array
        (
            [name] => User.One 
            [email] => [email protected]
        )

    [1] => Array
        (
            [name] => User.Two 
            [email] => [email protected]
        )

    [2] => Array
        (
            [name] => User.Three 
            [email] => [email protected]
        )
)

The problem I'm having is the run times are only added to the 10th element which is expected But I would like elements 0-9 to have the same run time and 10-20 etc. How would I achieve something like this??

2 Answers 2

1

Probably easier like this always adding runtime but updating it for each 10:

$time = '00:00:00';
foreach($agent_arr as $key => $value) {
    if($key % 10 === 0) {
        $temp = strtotime("+$k minutes", strtotime($time));
        $runTime = date('H:i', $temp);
    }
    $agent_arr[$key]['runtime'] = $runTime;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think you've left out the updating of the $k variable.
This is very neat. Thank you.
0

Here's my overcomplicated solution(and probably unnecessary):

$new_array = array();

foreach(array_chunk($array, 10 /* Your leap number would go here */) as $k => $v)
{
    array_walk($v, function($value, $key) use (&$new_array){
        $value['time'] = $time;
        $new_array[] = $value;
    });
}

Comments

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.