I might be punching slightly above my weight here or maybe its a really simple problem with a simple solution.
MY PROBLEM
- I cant access array key values in foreach()
- When creating the array in a function it seems that the array is duplicating, does a double iteration when created(as you can see in image below)
STEP 1: Array Creation
$results = $stmnt->fetchAll();
if ($stmnt->rowCount() > 0) {
$totalCorrectPicks = 0;
//--->HERE ARRAY KEYS ARE CREATED FROM QUERYING DB
foreach ($results as $index => $result) {
$returnResult = array('picked' => $result['team'], 'homeScore' => $result['homeScore'], 'awayScore' => $result['awayScore'], 'homeTeam' => $result['homeTeam'],
'awayTeam' => $result['awayTeam'], 'score' => $result['score']);
}//end foreach
//------> HERE ELEMENTS GETS APPENDED TO ARRAY
$pickedTeam = $result['team'];
if ($result['homeScore'] > $result['awayScore']) {
$matchOutcome = $result['homeTeam'];
$matchScore = $result['homeScore'];
$returnResults['matchOutcome'] = $matchOutcome;
$returnResults['matchScore'] = $matchScore;
}
if ($result['awayScore'] > $result['homeScore']) {
$matchOutcome = $result['awayTeam'];
$matchScore = $result['awayScore'];
$returnResults['matchOutcome'] = $matchOutcome;
$returnResults['matchScore'] = $matchScore;
}
if ($pickedTeam === $matchOutcome) {
$totalCorrectPicks++;
$margin = abs($matchScore - $result['points']);
//INDEX WILL START AT 0 SO WE ADD ONE TO $INDEX
$nrGames = $index + 1;
$returnResults['totatlCorrectPicks'] = $totalCorrectPicks;
$returnResults['margin'] = $margin;
$returnResults['nrGames'] = $nrGames;
}
elseif ($pickedTeam !== $matchOutcome) {
$margin = 'wrongPick';
$returnResults['margin'] = $margin;
}
}
}
if(isset($returnResults)){
print_r($returnResults);
return $returnResults;
}
return false;
}
STEP 2 Calling function and using array; leads to illegal string offset
<?php $picks = checkUserPicks('5');
foreach ($picks as $index => $pick){
?>
<tr>
<td>
<?php echo $pick['picked']; ?>
</td>
<td>
<?php echo $pick['matchOutcome']; ?>
</td>
<td>
<?php echo $pick['margin']; ?>
</td>
</tr>
<?php } ?>
NOTE: you can see the array value in the image posted above.
Questions
1) Why does it seem like the array is duplicated (see image)?
2) How can I fix the illegal string offset and what causes it?
Thanks
UPDATE
New Array Structure after removing [] from $returnResults[]

