我可能会在这里略微超过我的体重,或者通过一个简单的解决方案可能是一个非常简单的问题。
我的问题
第1步:阵列创建
$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;
}
步骤2调用函数并使用数组;导致非法字符串偏移
<?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 } ?>
注意:您可以在上面张贴的图片中看到数组值。
问题
1)为什么看起来数组是重复的(见图)?
2)如何修复非法字符串偏移及其原因?
由于
更新
从[]
中删除$returnResults[]
后的新阵列结构
答案 0 :(得分:1)
foreach
循环结束后,matchOutcome, matchScore
等会附加到数组中。它不应该在循环中吗?
如果您期望多行,则需要通过维护索引来创建数组,如下所示:
$returnResults = array(); // Initialize array
foreach ($results as $index => $result) {
$returnResults[$index] = array('picked' => $result['team'], 'homeScore' => $result['homeScore'],
'awayScore' => $result['awayScore'], 'homeTeam' => $result['homeTeam'],
'awayTeam' => $result['awayTeam'], 'score' => $result['score']);
//------> HERE ELEMENTS GETS APPENDED TO ARRAY
$pickedTeam = $result['team'];
if ($result['homeScore'] > $result['awayScore']) {
$matchOutcome = $result['homeTeam'];
$matchScore = $result['homeScore'];
$returnResults[$index]['matchOutcome'] = $matchOutcome;
$returnResults[$index]['matchScore'] = $matchScore;
}
.
.
elseif ($pickedTeam !== $matchOutcome) {
$margin = 'wrongPick';
$returnResults[$index]['margin'] = $margin;
}
}//end foreach