b0w3rb0w3r
b0w3rb0w3r

Reputation: 937

Adding elements to an Array using a special loop for iteration

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??

Upvotes: 0

Views: 61

Answers (2)

Andrei
Andrei

Reputation: 3588

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;
    });
}

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

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;
}

Upvotes: 1

Related Questions