【发布时间】:2018-07-06 12:37:10
【问题描述】:
我可能在这里打得比我的体重略高,或者它可能是一个非常简单的问题,有一个简单的解决方案。
我的问题
- 我无法在 foreach() 中访问数组键值
- 在函数中创建数组时,数组似乎在重复,创建时会进行两次迭代(如下图所示)
第 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;
}
STEP 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[] 中删除[] 后的新数组结构
【问题讨论】:
标签: php html arrays function multidimensional-array