devbox devbox -4 years ago 45
PHP Question

Creating a key-value pair in one foreach iteration, and reassigning the value in another

Background

I'm trying to figure out the actual playing time of a footballer (soccer player) in a given match. In other words, the time during which he was on the field as an active player.

Some user-inputted data is provided:


  • if and when the player was substituted, and whether he was subbed on or off

  • whether the player started the match on the pitch or on the bench

  • the start and end timestamps for each half of the match



Problem

I'm trying to create pairs of events, which represent a 'unit' of actual playing time. In this example, in the first iteration of the the outermost foreach, I create an array:

$aptPeriods = array(
'start' => 32,
'end' => ''
)

In the second iteration, the script identifies the empty 'end' value, and tries to reassign it.

$playerSubstitutions = array(
array(
'type' => 'on',
'time' => '38'
),
array(
'type' => 'off',
'time' => '68'
)
);

foreach($playerSubstitutions as $sub) {
// If the sub type is 'on', create a new aptPeriod and set the 'end' time to nothing
if($sub['type'] == 'on') {
$subOnEvent = array(
'start' => $sub['time'],
'end' => ''
);
array_push($aptPeriods, $subOnEvent);
// If the sub type is 'off', scan the aptPeriods array for an empty 'end' value, then set it to the subOff time
} elseif($sub['type'] == 'off') {
foreach($aptPeriods as $period) {
if($period['end'] == '') {
$period['end'] == $sub['time'];
}
}
}
}

echo '<pre>'; print_r($aptPeriods); echo '</pre>';


This returns:

Array
(
[0] => Array
(
[start] => 38
[end] =>
)

)


The innermost foreach is definitely executing, and
$sub['time']
is definitely set, but the blank 'end' value is not being reassigned. Where am I going wrong?

Answer Source

If you want to modify the original values then use...

     foreach($aptPeriods as &$period) {
            if($period['end'] == '') {
                $period['end'] = $sub['time'];
            }
        } 
    unset ($period);

(Note the & in the $period bit)

The foreach was making a copy of each array element and you were modifying that and not the original array.

Also - as pointed out, the == in the assignment is actually testing for equals, so this should just be a single =.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download